module.exports = {
	// 单个设备或者全部设备
	// 异常断开和主动断开
	// 异常需要执行重连
	// 蓝牙状态重置
	reset_bluetooth_cache(event = {}) {
		let _this = this;
		let { deviceId = false, ALL_CLEAR = false, REFRESH = false, callback = false } = event;
		let DEVICE_LIST = uni.getStorageSync('BLUETOOTH_DEVICE_LIST') || [];
		if (_this.objJudge(DEVICE_LIST)) {
			DEVICE_LIST.forEach(item => {
				if (deviceId) {
					// 重置某一个
					if (deviceId == item.bluetooth_deviceId) {
						item = _this.reset_bluetooth_fun(item);
					}
				} else {
					if (ALL_CLEAR) {
						item['bluetooth_break'] = 'hand_break';
					}
					// onlaunch初始化所有蓝牙设备 断开连接
					item = _this.reset_bluetooth_fun(item);
				}
			});
			uni.setStorageSync('BLUETOOTH_DEVICE_LIST', DEVICE_LIST);
			if (ALL_CLEAR || REFRESH) {
				_this.PAGE_CALLBACK();
			}
			if (callback) {
				callback();
			}
		}
	},
	//清除设备信息
	reset_bluetooth_fun(device) {
		let _this = this;
		let { bluetooth_deviceId, bluetooth_break } = device;
		// 手动断开设备--------------需要清空id
		let cache = uni.getStorageSync('bluetooth_close_cache') || {};
		if (_this.objJudge(cache)) {
			let { deviceId, data } = cache;
			if (deviceId == bluetooth_deviceId) {
				bluetooth_break = data.bluetooth_break;
				uni.removeStorageSync('bluetooth_close_cache');
			}
			// console.log(cache, bluetooth_break, 'reset_bluetooth_fun');
		}
		// 手动断开设备--------------需要清空id
		if (bluetooth_break == 'auto_break') {
			// 自动断开需要重新连接
		} else if (bluetooth_break == 'hand_break') {
			// 手动断开需要清除对应设备信息
			device['bluetooth_deviceId'] = '';
			device['bluetooth_device_info'] = {};
			device['bluetooth_device_mac'] = '-';
			device['bluetooth_device_name'] = '-';
			// 指令处理数据
			uni.removeStorageSync('cache_config');
			uni.removeStorageSync('cache_form');
			// 节流任务
			// uni.removeStorageSync('task_config');
		}
		device['bluetooth_connect'] = false;
		device['bluetooth_reconnect'] = false;
		device['bluetooth_serviceId'] = '';
		device['bluetooth_writeCharacteristicId'] = '';
		device['bluetooth_notifyCharacteristicId'] = '';
		device['bluetooth_serverList'] = [];

		return device;
	},

	bluetooth_close_cache(event) {
		let _this = this;
		let { deviceId, data } = event;
		uni.setStorageSync('bluetooth_close_cache', event);
	},

	//更新缓存最新的设备信息
	update_bluetooth_fun(event) {
		let _this = this;
		let { bluetooth_deviceId = false, update = {} } = event;
		let DEVICE_LIST = uni.getStorageSync('BLUETOOTH_DEVICE_LIST') || [];
		if (_this.objJudge(DEVICE_LIST) && bluetooth_deviceId) {
			DEVICE_LIST.map(item => {
				if (item.bluetooth_deviceId == bluetooth_deviceId) {
					Object.assign(item, update);
				}
				return item;
			});
			uni.setStorageSync('BLUETOOTH_DEVICE_LIST', DEVICE_LIST);
		}
	},
	clear_bluetooth_cache() {
		uni.removeStorageSync('BLUETOOTH_CHANGE_INIT');
		uni.removeStorageSync('BLUETOOTH_DEVICE_LIST');
		uni.removeStorageSync('cache_config');
		uni.removeStorageSync('cache_form');
		uni.removeStorageSync('system_setting_current_limit');
	},
	// 更新蓝牙设备
	UPDATE_STATE_BLUETOOTH_DEVICE(data) {
		let _this = this;
		_this.store_set_state_config({ state_name: 'BLUETOOTH_DEVICE_CONFIG', data });
	},
	// 已连接设备更新到页面
	update_pagedevice() {
		let _this = this;
		let DEVICE_LIST = uni.getStorageSync('BLUETOOTH_DEVICE_LIST') || [];
		let target = 'device_battery';

		if (_this.objJudge(_this.page_current_device)) {
			target = _this.page_current_device;
		}

		if (_this.objJudge(_this.current_device)) {
			target = _this.current_device;
		}
		let _init = {};
		for (let index = 0; index < _this.COMMON_VAR.BLUETOOTH_DEVICE_LIST.length; index++) {
			let _default = _this.COMMON_VAR.BLUETOOTH_DEVICE_LIST[index];
			// ------------------------
			let _cache = {};
			if (_this.objJudge(DEVICE_LIST)) {
				DEVICE_LIST.forEach(item => {
					if (item.bluetooth_device_type == _default.bluetooth_device_type) {
						_cache = item;
					}
				});
			}
			if (_this.objJudge(_cache)) {
				_default = _cache;
			}
			// ------------------------
			if (_default.bluetooth_device_type == target) {
				_init = _default;
			}
		}
		_this.UPDATE_STATE_BLUETOOTH_DEVICE(_init);
		// console.log('------------------------------更新设备');
		// console.log(_this.BLUETOOTH_DEVICE_CONFIG);
		// console.log(DEVICE_LIST);
		// console.log('------------------------------更新设备');

		// #ifdef MP-WEIXIN
		if (_init.bluetooth_connect) {
			_this.store_set_state_config({ state_name: 'BLUETOOTH_INIT_FORM', data: { dev_id: _init['bluetooth_device_mac'], bluetooth_device_name: _init['bluetooth_device_name'] } });
		} else {
			_this.BLUETOOTH_RESET_FORM();
		}
		// #endif
	},
	// 蓝牙指令回调更新到页面
	update_pagedata(page_echo) {
		let _this = this;

		if (_this.objJudge(page_echo)) {
			page_echo.forEach(vv => {
				let vv_type = _this.gettype(vv.value);
				switch (vv_type) {
					case 'Object':
						for (const k in vv.value) {
							// {k:v,k1:v1}
							// _this.page_form[k] = vv.value[k];
						}
						break;
					case 'Array':
						let config_item = vv;
						if (_this.objJudge(vv._item)) {
							config_item = vv._item;
						}
						let value_config_fun_back = _this.com_value_config_init(config_item, vv.value);
						if (_this.objJudge(value_config_fun_back)) {
							console.log(value_config_fun_back);
						}
						break;
					default:
						// _this.page_form[vv.key] = vv.value;
						break;
				}
			});
		}
	},

	judge_show_log(log) {
		let _this = this;
		if (_this.show_buffer) {
			console.log(log);
		}
	},

	// 扫码连接或者连接附近设备
	bluetooth_connect_menu(type = -1) {
		let _this = this;
		let page_login = _this.USER_LOGIN;

		function connect_fun(fun_type) {
			switch (fun_type) {
				case 0:
					_this.bluetooth_connect_qrcode();
					break;
				case 1:
					_this.bluetooth_list_open();
					break;
			}
		}

		switch (page_login) {
			case true:
				_this.bluetooth_init_judge({ click_trigger: true }, () => {
					// 初始化完成
					if (type > -1) {
						// 指定连接方式
						connect_fun(type);
					} else {
						// 菜单选择
						uni.showActionSheet({
							itemList: ['扫码连接', '附近设备'],
							success: function (res) {
								let { tapIndex } = res;
								connect_fun(tapIndex);
							},
							fail: function (res) {
								console.log(res.errMsg);
							},
						});
					}
				});
				break;

			case false:
				_this.$refs.pagelogin.page_login();
				break;
		}
	},

	bluetooth_connect_qrcode() {
		let _this = this;
		uni.scanCode({
			success: function (res) {
				let { bluetooth_connect, bluetooth_device_mac } = _this.BLUETOOTH_DEVICE_CONFIG;
				if (bluetooth_connect && bluetooth_device_mac == res.result) {
					_this.com_modal({
						content: '已连接该设备',
						confirmText: '我知道了',
						showCancel: false,
					});
					_this.store_set_state({ state_name: 'WORKING_SCAN', state_value: false });
				} else {
					_this.com_loading({
						status: 1,
						title: '扫描中...',
						throttle: false,
						timeout_limit: 5000,
						timeout_callback: () => {
							if (_this.SCAN_QRCODE_MAC) {
								if (_this.WORKING_SCAN) {
									_this.stop_scan({ log: true });
									_this.store_set_state({ state_name: 'SCAN_QRCODE_MAC', state_value: '' });
									// _this.pagerefresh();
									_this.com_msg('查找失败，请重试！', 2000, false, 'error');
								}
							}
						},
					});
					_this.store_set_state({ state_name: 'WORKING_SCAN', state_value: true });
					_this.store_set_state({ state_name: 'SCAN_QRCODE_MAC', state_value: res.result });
					_this.startBluetoothDevicesDiscovery();
					console.log('扫描成功', res.result);
				}
			},
			fail: function (res) {
				_this.store_set_state({ state_name: 'WORKING_SCAN', state_value: false });
				console.log('扫描失败', res);
			},
		});
	},

	bluetooth_list_open() {
		let _this = this;
		_this.$refs.bluetoothPopup.bluetoothPopup_init();
	},
	// 操作指令前判断是否登录是否连接设备
	bluetooth_operate_before_judge() {
		let _this = this;
		let page_login = _this.USER_LOGIN;
		let { bluetooth_connect } = _this.BLUETOOTH_DEVICE_CONFIG;

		if (_this.TEST_CONNECT) {
			// jojo
			return true;
		} else {
			if (page_login) {
				if (!bluetooth_connect) {
					return false;
				} else {
					return true;
				}
			} else {
				_this.$refs.pagelogin.page_login();
				return false;
			}
		}
	},

	// 1.蓝牙判断是否初始化
	bluetooth_init_judge(_config = {}, callback = false) {
		let _this = this;
		let { click_trigger = true, ischeck = false } = _config;
		if (click_trigger) {
			// 主动触发

			if (ischeck) {
				uni.getBluetoothAdapterState({
					// 本机蓝牙是否可用
					success(res) {
						console.log(`蓝牙API已初始化--蓝牙是否可用：${res.available}`);
						if (res.available) {
							_this.store_set_state({ state_name: 'BLUETOOTH_INIT', state_value: true });
							callback && callback();
						} else {
							_this.bluetooth_init_fun(_config, callback);
						}
					},
					fail(res) {
						// _this.com_update_log_scan_warn(
						// 	`蓝牙API未初始化${JSON.stringify(res)}`
						// );
						console.log('蓝牙API未初始化', res);
						if (res.errCode == 10000) {
							// 需要初始化 openBluetoothAdapter
							_this.bluetooth_init_fun(_config, callback);
						}
					},
				});
			} else {
				_this.check_permission({
					k: 'bluetooth',
					show_Modal: true,
					suc_fun: function () {
						_this.check_permission({
							k: 'location',
							show_Modal: true,
							suc_fun: function () {
								_this.bluetooth_init_judge({ click_trigger: true, ischeck: true }, callback);
							},
							fail_fun: function () {},
						});
					},
					fail_fun: function () {},
				});
			}
		} else {
			// 自动触发
			_this.check_permission({
				k: 'bluetooth',
				show_Modal: false,
				suc_fun: function () {
					_this.check_permission({
						k: 'location',
						show_Modal: false,
						suc_fun: function () {
							_this.bluetooth_init_judge({ click_trigger: true, ischeck: true }, callback);
						},
						fail_fun: function () {
							// console.log('no');
						},
					});
				},
				fail_fun: function () {
					// console.log('no');
				},
			});
		}
	},
	// 2.蓝牙初始化
	bluetooth_init_fun(_config = {}, callback = false) {
		let _this = this;
		uni.openBluetoothAdapter({
			success: () => {
				console.log('bluetooth_init_fun--蓝牙初始化成功');
				_this.store_set_state({ state_name: 'BLUETOOTH_INIT', state_value: true });
				_this.bluetooth_init_onchange();
				// _this.com_update_log_scan_warn(`蓝牙初始化成功`);
				callback && callback();
			},
			fail: async res => {
				console.log('bluetooth_init_fun--蓝牙初始化失败', res);
				_this.com_update_log_scan_warn(`蓝牙初始化失败${JSON.stringify(res)}`);
				_this.store_set_state({ state_name: 'BLUETOOTH_INIT', state_value: false });
				_this.bluetooth_init_onchange();
				// #ifdef MP-WEIXIN
				if (res.errno == 4 || res.errno == 3) {
					// 安卓没开启附近的设备权限
					let _bluetooth = await _this.com_modal({
						title: `权限申请`,
						content: '在应用信息-权限中开启附近的设备权限，以正常使用扫描周边、连接等功能',
						// confirmText: '我知道了',
						showCancel: true,
					});
					if (_bluetooth) {
						uni.openAppAuthorizeSetting();
					} else {
					}
					return;
				}

				if (res.errno == 104) {
					// 隐私政策未同意
					// _this.com_msg('');
					_this.com_modal({ content: '蓝牙初始化失败' });
					return;
				}
				if (res.errCode === 10001) {
					if (_this.objJudge(res.state) && res.state == 3) {
						// 用户已授权但是没有打开手机的蓝牙功能 提示用户开启蓝牙功能
						// _this.bluetooth_init_author_judge();
						// return;
					} else {
						_this.com_modal({
							content: '请开启手机蓝牙功能',
							confirmText: '我知道了',
							showCancel: false,
						});
						// _this.com_msg('请开启手机蓝牙功能');
						return;
					}
				}
				// #endif
			},
		});
	},

	// 判断当前蓝牙设备和历史连接设备是否存在 存在直连进行初始化
	async judge_has_connect(config) {
		let _this = this;
		let { task = false, loop_time = 5000 } = config;
		let { bluetooth_connect, bluetooth_reconnect, bluetooth_device_mac, bluetooth_deviceId } = _this.BLUETOOTH_DEVICE_CONFIG;
		// 只重连一次
		let can_connect = true;
		// 缓存有上次连接的设备记录 尝试连接
		if (!_this.objJudge(bluetooth_deviceId) || !_this.objJudge(bluetooth_device_mac) || !_this.BLUETOOTH_INIT) can_connect = false;
		if (bluetooth_connect || _this.WORKING_SCAN || bluetooth_reconnect) can_connect = false;
		console.log({
			bluetooth_deviceId,
			bluetooth_device_mac,
			bluetooth_init: _this.BLUETOOTH_INIT,
		});
		console.log({
			bluetooth_connect,
			WORKING_SCAN: _this.WORKING_SCAN,
			bluetooth_reconnect,
			can_connect,
		});
		if (can_connect) {
			// 暂时允许重连一次 jojo
			_this.UPDATE_STATE_BLUETOOTH_DEVICE({ bluetooth_reconnect: true });
			_this.com_loading({ status: 1, type: 'loading', title: '重新连接...', throttle: false });
			_this.change_var['timeout_loading'] = true;
			_this.create_connect_judge(bluetooth_deviceId, bluetooth_device_mac);
		} else {
			// if (task && !bluetooth_connect) {
			// 	setTimeout(() => {
			// 		_this.judge_has_connect(config);
			// 	}, loop_time);
			// }
		}
	},

	// 扫描周边设备
	startBluetoothDevicesDiscovery() {
		let _this = this;
		let connect_mac = _this.SCAN_QRCODE_MAC || false;
		let { UUID_PRIMARY_SERVICE = '' } = _this.BLUETOOTH_DEVICE_CONFIG || {};
		_this.change_var.bluetooth_scan_log_list = [];
		uni.startBluetoothDevicesDiscovery({
			services: [],
			allowDuplicatesKey: true,
			success: res => {
				console.log('startBluetoothDevicesDiscovery', res);
				//  寻找新设备
				uni.onBluetoothDeviceFound(res => {
					let { res_deviceId, res_mac = false } = _this.get_deviceId_info(res.devices[0]);
					// 查找附近设备
					let _device = res.devices[0];
					_device['advertisData_hex'] = _this.ab2hex(_device.advertisData);
					_device['res_deviceId'] = res_deviceId;
					_device['res_mac'] = res_mac;
					_device['list_name'] = '未知设备';
					if (_this.objJudge(_device.localName)) {
						_device['list_name'] = _device.localName;
					}
					if (_this.objJudge(_device.name)) {
						_device['list_name'] = _device.name;
					}
					_device['list_id'] = res_deviceId;
					if (_this.objJudge(_device.res_mac)) {
						_device['list_id'] = _device.res_mac;
					}
					// ----------------------------日志
					let _log = {
						connect: res_deviceId,
						back: res_mac,
						hex: _device['advertisData_hex'],
						scan: connect_mac,
					};
					let scan_i = _this.change_var.bluetooth_scan_log_list.findIndex(item => {
						return item.connect == _log.connect;
					});
					if (scan_i > -1) {
						_this.change_var.bluetooth_scan_log_list[scan_i] = _log;
					} else {
						_this.change_var.bluetooth_scan_log_list.push(_log);
					}
					// ----------------------------日志
					if (connect_mac) {
						// 扫描二维码进行连接
						if (res_mac && res_mac == connect_mac) {
							_this.stop_scan();
							_this.create_connect_judge(res_deviceId, res_mac, _device);
						}
					} else {
						// 添加到列表进行点击连接
						let index = _this.page_device_list.findIndex(item => {
							return item.deviceId == res_deviceId;
						});
						if (res_mac) {
							if (index > -1) {
								_this.page_device_list[index] = _device;
							} else {
								_this.page_device_list.push(_device);
							}
						}
					}
				});
			},
			fail: async res => {
				_this.com_update_log_scan_warn(`扫描错误：${JSON.stringify(res)}`);
				console.log('无法开始扫描', res);

				_this.store_set_state({ state_name: 'SCAN_QRCODE_MAC', state_value: '' });
				_this.store_set_state({ state_name: 'WORKING_SCAN', state_value: false });
				// #ifdef MP-WEIXIN
				if (res.errno == 1509008) {
					// 微信没开启位置权限
					let _bluetooth = await _this.com_modal({
						title: `权限申请`,
						content: '在应用信息-权限中开启位置信息权限，以正常使用扫描周边设备功能',
						// confirmText: '我知道了',
						showCancel: true,
					});
					if (_bluetooth) {
						uni.openAppAuthorizeSetting();
					} else {
					}
					return;
				}
				// #endif
			},
		});
	},
	get_deviceId_info(dev) {
		let _this = this;
		let res_deviceId = dev.deviceId;
		let res_mac = dev.deviceId;
		let normal_mac = false;

		if (_this.objJudge(_this.COMMON_VAR.is_ios)) {
			let BACK = _this.back_mac(dev.advertisData);
			res_mac = BACK['rever'];
			// normal_mac = BACK['normal'];
		}
		return {
			res_deviceId,
			res_mac,
			// normal_mac,
		};
	},
	// 扫描失败上传日志
	com_update_log_scan_warn(array) {
		let _this = this;
		let msg = JSON.stringify(array);
		// console.log(_list, data)
		_this.com_getdata({
			url: '/test/log',
			data_handle_on: false,
			id_name: 'user_id',
			data: {
				msg,
			},
		});
	},
	ab2hex(buffer, symbol = '') {
		let _this = this;
		let type = _this.gettype(buffer);
		let hexString;
		switch (type) {
			case 'ArrayBuffer':
				// ArrayBuffer转16进制字符串示例
				hexString = Array.prototype.map
					.call(new Uint8Array(buffer), function (bit) {
						return ('00' + bit.toString(16).toUpperCase()).slice(-2);
					})
					.join(symbol);

				break;
			case 'Array':
				// 十进制数组转十六进制字符串示例
				hexString = buffer
					.map(function (decimal) {
						let n = decimal.toString(16).toUpperCase();
						while (n.length < 2) {
							n = '0' + n;
						}
						return n; // 使用toString方法，指定基数为16，然后将结果转为大写
					})
					.join(symbol);
				break;
		}
		return hexString;
	},

	// ios处理id返回mac地址进行二维码配对
	convertToMacAddress(str) {
		if (str) {
			let new_mac = false;
			let judge_str = str.substring(0, 6).toUpperCase();
			if (judge_str == 'A5C237' || judge_str == '616C69') {
				new_mac = true;
			}
			// 分割字符串成两个字符一组
			let groups = str.match(/.{1,2}/g);
			if (new_mac) {
			} else {
				groups = groups.reverse();
			}
			// 反转组并用冒号连接
			let reversedMacAddress = groups.join(':');
			return reversedMacAddress.toUpperCase();
		} else {
			return '';
		}
	},

	// 停止扫描操作
	stop_scan(config = {}) {
		let _this = this;
		let { log = false } = config;
		if (_this.WORKING_SCAN) {
			_this.store_set_state({ state_name: 'WORKING_SCAN', state_value: false });
			uni.stopBluetoothDevicesDiscovery();
			console.log('停止扫描操作');
		}
		if (log) {
			_this.com_update_log_scan_warn(_this.change_var.bluetooth_scan_log_list);
		}
		// console.log(_this.change_var.bluetooth_scan_log_list);
	},
	// 设置设备唯一mac地址
	// 直连需要解析  扫码就直接获取
	back_mac(buffer) {
		let _this = this;
		let t = Array.from(new Uint8Array(buffer));
		t = t.slice(0, 6);

		return {
			rever: _this.convertToMacAddress(_this.ab2hex(t)),
		};
	},

	check_dev(dev_id) {
		let _this = this;
		return new Promise((rs, rj) => {
			_this.com_getdata({
				url: `/device/code`,
				data: {
					dev_id,
				},
				log: false,
				data_fun: function (res) {
					if (res.state == 1) {
						let { user_id } = res.data;
						let _f = null;
						if (_this.objJudge(user_id)) {
							// 有返回id说明已给绑定
							let _myuserid = uni.getStorageSync('userid');
							if (_myuserid == user_id) {
								// 是我的设备则直连
								_f = 1;
							} else {
								// 不是我的提示已给绑定
								_f = -1;
							}
						} else {
							// 无user_id则可以绑定
							_f = 0;
						}
						rs(_f);
					} else {
						// 后台没有这个设备数据
						_this.com_update_log_scan_warn(`未录入系统：${dev_id}`);

						rs(-2);
					}
				},
			});
		});
	},

	// 创建连接
	create_connect(deviceId, DEVICE = false) {
		let _this = this;
		// _this.com_loading({ status: 1, type: 'loading', title: '创建连接...', throttle: false, loading_log: true });
		uni.createBLEConnection({
			deviceId,
			timeout: _this.timeout,
			success: res => {
				_this.change_var['timeout_loading'] = false;
				_this.com_loading({ status: 1, type: 'loading', title: '连接中...', throttle: false });
				if (DEVICE) {
					uni.setStorageSync('READY_DEVICE', DEVICE);
				}
				console.log('1.---创建连接成功' + deviceId);
				// setBLEMTU在安卓才生效
				// if (_this.COMMON_VAR.platform == 'android') {
				//     uni.setBLEMTU({
				//         deviceId,
				//         mtu: 512,
				//         success: (res) => {
				//             console.log("setBLEMTU success>>", res)
				//         },
				//         fail: (res) => {
				//             console.log("setBLEMTU fail>>", res)
				//         }
				//     })
				// }
				// setBLEMTU在安卓才生效
				setTimeout(() => {
					_this.get_server(deviceId);
				}, 1000);
			},
			fail(e) {
				console.log(e, deviceId, _this.change_var['timeout_loading'], '创建连接失败');
				if (_this.change_var['timeout_loading']) {
					_this.com_loading({ status: 1, type: 'msg', title: '自动重连失败，请手动连接', throttle: false, loading_log: true });
				} else {
					_this.com_loading({ status: 1, type: 'msg', title: '连接失败，请重试', throttle: false, loading_log: true });
				}
				_this.com_update_log_scan_warn(`${deviceId}--创建连接失败${JSON.stringify(e)}--手机:${_this.COMMON_VAR['phone_info']}`);
			},
		});
	},
	close_connect(deviceId, callback = false) {
		let _this = this;
		if (!deviceId) return;
		uni.closeBLEConnection({
			deviceId,
			success(res) {
				_this.bluetooth_close_cache({
					deviceId,
					data: { bluetooth_break: 'hand_break' },
				});
				callback && callback();
				console.log(res, 'closeBLEConnection---手动断开连接');
			},
			fail(res) {
				console.log(res, 'closeBLEConnection---手动断开连接失败');
			},
		});
	},
	//获取蓝牙服务
	get_server(deviceId) {
		const _this = this;
		_this.change_var.BLUETOOTH_DEVICE_TEMP['bluetooth_serverList'] = [];
		uni.getBLEDeviceServices({
			deviceId,
			success: function (res) {
				console.log('2.获取蓝牙服务', res);
				for (let i = 0; i < res.services.length; i++) {
					// res.services[i]
					// uuid	string	蓝牙设备服务的 uuid
					// isPrimary	boolean	该服务是否为主服务
					// if (res.services[i].uuid.indexOf('fff0') > -1 || res.services[i].uuid.indexOf('FFF0') > -1) {
					_this.change_var.BLUETOOTH_DEVICE_TEMP['bluetooth_serverList'].push(res.services[i]);
					setTimeout(() => {
						_this.get_characteristic(deviceId, res.services[i].uuid, i);
					}, 300);
					// }
				}
			},
			fail(e) {
				console.log('error2', e);
			},
		});
	},
	// 根据 deviceId, serviceId 获取特征列表
	get_characteristic(deviceId, serviceId, serve_i) {
		const _this = this;
		uni.getBLEDeviceCharacteristics({
			deviceId,
			serviceId,
			success: res => {
				console.log(`3.获取蓝牙服务_${serve_i + 1}_的所有特征值成功`, res.characteristics);
				_this.change_var.BLUETOOTH_DEVICE_TEMP['bluetooth_serverList'][serve_i]['characteristics'] = res.characteristics;
				for (let i = 0; i < res.characteristics.length; i++) {
					let item = res.characteristics[i];
					if (item.properties.read) {
						// uni.readBLECharacteristicValue({
						// 	deviceId,
						// 	serviceId,
						// 	characteristicId: item.uuid,
						// 	success(res) {
						// 		// console.log(res, '读取特征值成功')
						// 	},
						// 	fail(res) {
						// 		console.log(res, '读取特征值失败');
						// 	},
						// });
					}

					let _target = item.uuid.toUpperCase();
					// -------------------------
					let can_write = _target.indexOf(_this.BLUETOOTH_DEVICE_CONFIG.UUID_WRITE_SCREEN) > -1 && item.properties.write ? true : false;
					if (can_write) {
						_this.set_device(deviceId, serviceId, item.uuid);
					}
					// -------------------------
					let can_notify = _target.indexOf(_this.BLUETOOTH_DEVICE_CONFIG.UUID_NOTIFY_SCREEN) > -1 && item.properties.notify ? true : false;

					if (can_notify) {
						_this.notifyValueChange(deviceId, serviceId, item.uuid);
					}
					// -------------------------
				}
				// 握手
				// if (_this.data.isNotify && _this.data.canWrite) {
				// 	_this.acceptReq()
				// }
			},
			fail(res) {
				console.log(deviceId);
				console.log(`蓝牙服务_${serve_i}_获取特征值失败: ${serviceId} `, res);
			},
		});
	},

	// 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
	notifyValueChange(deviceId, serviceId, characteristicId) {
		let _this = this;
		wx.notifyBLECharacteristicValueChange({
			deviceId,
			serviceId,
			characteristicId,
			state: true,
			success(res) {
				console.log('5.启用特征值变化监听成功---', characteristicId);
				_this.UPDATE_STATE_BLUETOOTH_DEVICE({ bluetooth_notifyCharacteristicId: characteristicId });
				// 避免循环的时候二次更改了写入特征UUID
				_this.onValueChange();
				// 读取UUID设置后执行回调
				_this.init_device_callback('notify');
			},
			fail(res) {
				console.log('5.监听数据失败3: ', res);
			},
		});
	},

	// 低功耗蓝牙设备的特征值变化
	// 必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
	onValueChange() {
		let _this = this;
		console.log('6.开始监听数据');
		wx.onBLECharacteristicValueChange(res => {
			let bufferValue = res.value;
			// console.log(res);
			_this.judge_show_log(`7.某个特征值变化--${res.characteristicId}`);

			// 初始化为十进制数据数组
			let { t: ten_arr, s: six_arr } = _this.log_buffer(bufferValue);
			// console.log(`8.十进制数据数组--${ten_arr}`);
			let { buffer_arr, start_code, cmd, page_arr } = _this.get_bluetooth_read_temp(ten_arr);
			// console.log(`9.某个特征值变化--${buffer_arr}`);
			// console.log(buffer_arr, page_arr);
			// buffer_arr为对应指令返回的最后数据 因为会有多次返回的情况，所以要进行拼接判断

			if (!_this.objJudge(buffer_arr)) {
				// console.log(six_arr, buffer_arr, 'buffer_arr');
				return;
			} else {
				// console.log(six_arr, buffer_arr, 'buffer_arr');
			}

			// 内部函数对指令进行分发处理数据到 页面的SOTRE对象中
			_this.init_page_buffer(start_code, cmd, page_arr, buffer_arr);
			_this.log_buffer(buffer_arr, '【响应完成-222222222222222】', true);
		});
	},

	// 监听手机蓝牙状态开启关闭
	bluetooth_init_onchange() {
		let _this = this;
		// 控制只挂载一次否则会多次挂载
		let BLUETOOTH_CHANGE_INIT = uni.getStorageSync('BLUETOOTH_CHANGE_INIT') || false;
		if (!BLUETOOTH_CHANGE_INIT) {
			uni.setStorageSync('BLUETOOTH_CHANGE_INIT', true);
			uni.onBluetoothAdapterStateChange(function (res) {
				let { available, discovering } = res;
				if (discovering) {
					console.log('---------扫描设备');
				} else {
					console.log('---------停止扫描');
					if (available) {
						console.log('---------蓝牙可用');
						_this.store_set_state({ state_name: 'BLUETOOTH_INIT', state_value: true });
						_this.PAGE_CALLBACK();
					} else if (!available) {
						console.log('---------蓝牙不可用');
						_this.store_set_state({ state_name: 'BLUETOOTH_INIT', state_value: false });
						_this.reset_bluetooth_cache({ REFRESH: true });
					}
				}
			});
			uni.onBLEConnectionStateChange(res => {
				console.log('设备连接状态', res);
				let { connected, deviceId } = res;
				// 该方法回调中可以用于处理连接意外断开等异常情况
				if (connected == true) {
				} else if (connected == false) {
					_this.reset_bluetooth_cache({
						deviceId,
						callback: function () {
							_this.update_pagedevice();
						},
					});
				}
			});
		}
	},

	//设置设备id
	set_device(deviceId, serviceId, writeCharacteristicId) {
		let _this = this;
		_this.UPDATE_STATE_BLUETOOTH_DEVICE({
			bluetooth_deviceId: deviceId,
			bluetooth_serviceId: serviceId,
			bluetooth_writeCharacteristicId: writeCharacteristicId,
		});
		// 写入UUID设置后执行回调
		_this.init_device_callback('write');
	},

	init_device_callback(t) {
		let _this = this;
		let _write = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_writeCharacteristicId;
		let _notify = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_notifyCharacteristicId;
		// let _change = uni.getStorageSync('ValueChange_back') || false;
		// 7.不像BMS会触发回调 所以不需要等待设备发送完后再创建连接
		// 可能是没有执行读取 read操作
		let _change = true;
		// console.log({
		// 	_write,
		// 	_notify,
		// 	_change,
		// 	t,
		// 	CONFIG,
		// });
		if (_write && _notify && _change) {
			console.log('写入特征id读取特征id设置完成再执行页面回调');
			_this.bluetooth_can_write = true;
			let DEVICE_LIST = uni.getStorageSync('BLUETOOTH_DEVICE_LIST') || [];
			let READY_DEVICE = uni.getStorageSync('READY_DEVICE') || {};

			// ------------------------------------ 更新到store全局管理
			let _update = { bluetooth_connect: true };
			if (_this.objJudge(READY_DEVICE)) {
				_update['bluetooth_device_info'] = READY_DEVICE;
				_update['bluetooth_device_mac'] = READY_DEVICE.res_mac;
			}
			Object.assign(_update, _this.change_var.BLUETOOTH_DEVICE_TEMP);
			_this.UPDATE_STATE_BLUETOOTH_DEVICE(_update);

			// ------------------------------------ 缓存更新下次重启应用可以重连
			let index = DEVICE_LIST.findIndex(item => {
				return item.bluetooth_device_type == _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_device_type;
			});
			if (index > -1) {
				DEVICE_LIST[index] = _this.BLUETOOTH_DEVICE_CONFIG;
			} else {
				DEVICE_LIST.push(_this.BLUETOOTH_DEVICE_CONFIG);
			}
			uni.setStorageSync('BLUETOOTH_DEVICE_LIST', DEVICE_LIST);
			// ------------------------------------

			let { bluetooth_deviceId, bluetooth_device_mac, bluetooth_device_info } = _this.BLUETOOTH_DEVICE_CONFIG;
			_this.com_update_log_scan_warn(
				`创建连接成功,连接id:${bluetooth_deviceId},hex数据:${bluetooth_device_info.advertisData_hex},mac地址:${bluetooth_device_mac},设备名称:${bluetooth_device_info.list_name},手机:${_this.COMMON_VAR['phone_info']}`
			);
			typeof _this.connect_callback == 'undefined' ? false : _this.connect_callback();
		}
	},

	BLUETOOTH_RESET_FORM() {
		let _this = this;
		let RESET = uni.getStorageSync('BLUETOOTH_INIT_RESET_FORM');
		if (_this.objJudge(RESET)) {
			_this.store_set_state_config({ state_name: 'BLUETOOTH_INIT_FORM', data: RESET });
		}
	},

	test_read(str) {
		let _this = this;
		let ttt = _this.str_to_buffer(str, true).num_arr;

		let { buffer_arr, start_code, cmd, page_arr } = _this.get_bluetooth_read_temp(ttt);

		_this.init_page_buffer(start_code, cmd, page_arr, buffer_arr);

		_this.log_buffer(buffer_arr, '【测试响应-222222222222222】', true);
	},
	// hex字符串转数组
	str_to_buffer(str, log = false) {
		let _this = this;

		let str_arr = str.toUpperCase().match(/.{1,2}/g);
		let num_arr = str_arr.map(vv => {
			return _this.stt(vv);
		});
		let back_str = str_arr.join('');
		if (log && _this.show_buffer) {
			console.log({
				str_arr,
				num_arr,
				back_str,
			});
		}

		return {
			str_arr, //十六进制数组
			num_arr, //十进制数组
			back_str,
		};
	},

	// 判断是否可执行蓝牙命令
	judge_bluetooth(callback, fail_callback) {
		let _this = this;
		// 连接上了设备并且是在当前页面
		if (_this.TEST_CONNECT) {
			// 开发环境方便测试
			return true;
		} else {
			let _canbluetooth = true;

			if (!_this.BLUETOOTH_DEVICE_CONFIG.bluetooth_connect) _canbluetooth = false;
			// if (!_this.change_var.page_canshow) _canbluetooth = false;
			if (_this.WORKING_SCAN || _this.WORKING_PAY || _this.WORKING_SELECT_FILE) _canbluetooth = false;

			// console.log(
			// 	_this.BLUETOOTH_DEVICE_CONFIG.bluetooth_connect,
			// 	_this.change_var.page_canshow,
			// 	_this.WORKING_SCAN,
			// 	_this.WORKING_PAY,
			// 	_this.WORKING_SELECT_FILE,
			// 	_canbluetooth,
			// 	'judge_bluetooth'
			// );
			if (_canbluetooth) {
				callback && callback();
				return true;
			} else {
				fail_callback && fail_callback();
				return false;
			}
		}
	},
	// 打印数据并且返回
	log_buffer(buffer, tt = '', end = false) {
		let _this = this;
		let show = true;

		let t = Array.from(new Uint8Array(buffer));

		// let s_2 = _this.deepclone(t)
		// let s_2_arr = s_2.map((vv) => {
		//     return _this.tts(vv, false);
		// })
		// console.log(t);

		let s = t.map(vv => {
			return _this.tts(vv);
		});
		if (_this.show_buffer && tt) {
			if (!end) {
				console.log(`log_buffer------------${tt}-start`);
				console.log(this.ab2hex(t));
				console.log(this.ab2hex(buffer));
				console.log(JSON.stringify(t)); // 十进制数组
				console.log(JSON.stringify(s)); // 十六进制数组
				console.log(`------------`);
				// console.log(s_2_arr.join(' ')) // 十六进制数组
				// console.log(s_2_arr.length) // 十六进制数组
			} else {
				console.log(`------------`);

				console.log(this.ab2hex(buffer));
				// console.log(s_2_arr.join(' ')) // 十六进制数组
				console.log(`log_buffer------------${tt}-end`);
			}
		}
		return {
			t, // 十进制数组
			s, // 十六进制数组
		};
	},

	// 蓝牙数据预处理 多次包等情况
	get_bluetooth_read_temp(v) {
		let _this = this;
		let _temp = _this.bluetooth_read_temp;
		let buffer_arr = v;
		if (_this.objJudge(_temp)) {
			// 有数据需要拼接
			buffer_arr = _temp.concat(v);
		}
		let start_code = buffer_arr[0]; //开始码
		let cmd = buffer_arr[1]; //指令码
		// 起始位0xdd 命名码0x03 状态码00 业务数据长度（不包括自身）26  fa,6b校验码 77结束码
		// [0xdd,0x03,00,26,15....,fa,6b,77]
		let page_arr;
		if (start_code == 0xff && cmd == 0xaa) {
			// 获取mac地址
			page_arr = buffer_arr.slice(4, 4 + buffer_arr[3]);
		} else {
			// 正常指令业务数据
			page_arr = buffer_arr.slice(4, buffer_arr.length - 3);
		}
		let v_length = buffer_arr[3]; // 业务数据的长度应该有多少
		// let v_end = buffer_arr[buffer_arr.length - 1]; //响应结束码
		// 连接后设备会自动响应两个信息
		// [119, 101, 113, 119, 101, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
		//  0x77会导致 bluetooth_can_write为false进行阻塞  因为取了 第三位 113为长度需要添加多一个判断
		// console.log(v_length, page_arr, buffer_arr, start_code, 'get_bluetooth_read_temp调试')
		if (v_length > page_arr.length && page_arr.length > 0 && start_code != 0x77) {
			// 还有下一个数据包，一次传不完
			_this.bluetooth_read_temp = buffer_arr;
			_this.bluetooth_can_write = false;
			buffer_arr = [];
			page_arr = [];
		} else {
			_this.bluetooth_read_temp = [];
			_this.bluetooth_can_write = true;
		}
		return {
			buffer_arr,
			cmd,
			start_code,
			page_arr,
		};
	},
	/**
	 * 根据指令初始化页面数据到
	 * @param {number} cmd 读取指令  config[cmd]取到对应指令解析的配置
	 * @param {Array} page_buffer 指令返回的参数
	 * @param {Array} all_buffer 整个指令返回的参数
	 */
	init_page_buffer(start_code, cmd, page_buffer, all_buffer) {
		// let _this = this;
		let _this = getApp().globalData._this;
		// let INIT_FORM = uni.getStorageSync('cache_form') || {};
		let INIT_FORM = {};
		// 解析指令可视化
		let _echo = [];
		// let _alldata = _this.BLUETOOTH_ALL_DATA;
		let { bluetooth_deviceId } = _this.BLUETOOTH_DEVICE_CONFIG;
		// console.log(this.ab2hex(all_buffer), '返回数据')
		// console.log(page_buffer, all_buffer, 'all_buffer')
		// 默认指令 读取mac地址 蓝牙名称等  FFAA000000-------------------------------------
		if (start_code == 0xff && cmd == 0xaa) {
			// && all_buffer[3] > 0

			let instruct = all_buffer[2];

			let _back_instruct = null;

			if (instruct == 0x00) {
				// 查询mac地址 定义 0xF9 只做区分用
				let _mac = _this.ab2hex(all_buffer.slice(4, 4 + all_buffer[3]), ':');
				_back_instruct = 0xf9;
				_this.update_bluetooth_fun({
					bluetooth_deviceId,
					update: { bluetooth_device_mac: _mac },
				});
			}

			if (instruct == 0x06) {
				// 查询蓝牙名称 定义0xF8 只做区分用
				let back_name = page_buffer
					.map(item => {
						return _this.back_ascii_number(item);
					})
					.join('');
				_this.update_bluetooth_fun({
					bluetooth_deviceId,
					update: { bluetooth_device_name: back_name },
				});
				_back_instruct = 0xf8;
				if (_this.show_buffer) {
					console.log(back_name, page_buffer, '查询蓝牙名称---instruct0x06');
				}
			}
			if (instruct == 0x07) {
				// 修改蓝牙名称
				let index_bluetooth_name_cache = uni.getStorageSync('index_bluetooth_name_cache');
				_back_instruct = instruct;

				_this.update_bluetooth_fun({
					bluetooth_deviceId,
					update: { bluetooth_device_name: index_bluetooth_name_cache },
				});
				uni.removeStorageSync('index_bluetooth_name_cache');
			}
			_this.update_pagedevice();
			// console.log('start_code == 0xff');
			_this.responseInstruct(_back_instruct, _echo);
			return;
		}
		// 读取mac地址 指令  FFAA000000-------------------------------------

		// 设定的指令
		// 指令对应解析的参数
		let config = {
			0: {
				// 0x00
				tips: '进入工厂模式成功',
			},
			1: {
				// 0x01
				tips: '退出工厂模式成功',
			},
			3: {
				// 0x03
				tips: '基本信息及状态返回',
				config_list: [
					{
						key: 'dev_voltage',
						name: '总电压',
						byte: 2,
					},
					{
						key: 'dev_current',
						name: '电流',
						byte: 2,
						value_type: 'is_current',
					},
					{
						key: 'dev_capacity',
						name: '剩余容量',
						byte: 2,
					},
					{
						key: 'BatteryCapacity',
						name: '标称容量',
						byte: 2,
					},
					{
						key: 'dev_circulate',
						name: '循环次数',
						byte: 2,
					},
					{
						key: 'index_production_date',
						name: '生产日期',
						byte: 2,
						value_type: 'produce_date',
					},
					{
						key: 'index_balance_status',
						name: '均衡状态',
						byte: 2,
						value_type: 'binary_system',
					},
					{
						key: 'index_balance_status_high',
						name: '均衡状态_高',
						byte: 2,
						value_type: 'binary_system',
					},
					{
						key: 'index_protection_status',
						name: '保护状态',
						byte: 2,
						value_config_tips: [
							'单体过压保护',
							'单体欠压保护',
							'整组过压保护',
							'整组欠压保护',
							'充电过温保护',
							'充电低温保护',
							'放电过温保护',
							'放电低温保护',
							'充电过流保护',
							'放电过流保护',
							'短路保护',
							'前端检测IC错误',
							'软件锁定MOS',
							'充电MOS击穿标志',
							'放电MOS击穿标志',
							'预留',
						],
						value_type: 'binary_system',
					},
					{
						key: 'index_software_version',
						name: '软件版本',
						byte: 1,

						value_type: 'version',
					},
					{
						key: 'dev_soc',
						name: 'RSOC',
						byte: 1,
					},
					{
						key: 'index_FET_control_status',
						name: 'FET控制状态',
						byte: 1,
						// bit0表示充电MOS，bit1表示放电MOS  BIT2表示限流模块是否开启 BIT3表示加热是否开启
						// BIT7用来表示电流容量单位，如果最高位为1则表示电流容量单位是0.1A/0.1Ah
						form_config: ['index_charge_switch', 'index_discharge_switch', 'current_limiting_switch', 'heat_switch', '', '', '', 'current_capacity_unit'],
						value_type: 'binary_system_8',
					},
					{
						key: 'dev_bunch',
						name: '电池串数',
						byte: 1,
					},
					{
						key: 'dev_ntc',
						name: 'NTC个数',
						byte: 1,

						byte_list: true,
					},
					{
						key: 'index_NTC_content',
						name: 'NTC内容',
						byte: 2,

						value_type: 'NTC_content',
					},
					{
						key: 'dev_humidity',
						name: '湿度',
						byte: 1,
					},
					{
						key: 'index_alarm_status',
						name: '告警状态',
						byte: 2,

						value_config_tips: [
							'单体高压告警',
							'单体低压告警',
							'整组高压告警',
							'整组低压告警',
							'充电高温告警',
							'充电低温告警',
							'放电告温告警',
							'放电低温保护',
							'充电电流大告警',
							'放电电流大告警',
							'单体压差大告警',
							'容量低告警',
							'预留',
							'预留',
							'预留',
							'预留',
						],
						value_type: 'binary_system',
					},
					{
						key: 'index_full_charge_capacity',
						name: '满充容量',
						byte: 2,
					},
					{
						key: 'dev_capacity_2',
						name: '剩余容量',
						byte: 2,
					},
					{
						key: 'index_balance_current',
						name: '均衡电流',
						byte: 2,
					},
				],
			},
			4: {
				// 0x04
				tips: '电池的电压集合返回',
			},
			10: {
				// 0x0A
				tips: '自动均衡清除告警重置容量指令-执行返回',
			},
			170: {
				// 0xAA
				tips: '保护板历史保护次数',
			},
			246: {
				// 0xF6
				tips: '电池内阻30串',
			},
			250: {
				// 0xFA   DD FA 00 07后面数据长度  00 01序号开始  02个     [0F A0 10 36] FF 01 77
				// DDFA000B 0075 04 024C 0032 0032 050F FEB677
				tips: '参数读取成功返回对应的',
				config_list: {
					0: {
						name: '标称容量',
						key: 'initialize_nominal_capacity',
						byte: 2,
						unit: 'mAh',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 0,
						index_next: 1,
					},
					1: {
						name: '循环容量',
						key: 'initialize_cycle_capacity',
						byte: 2,
						unit: 'mAh',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 1,
						index_next: 2,
					},
					2: {
						name: '充满电压',
						key: 'capacity_voltage_setting_full_voltage',
						byte: 2,
						unit: 'mV',
						index: 2,
						index_next: 3,
					},
					3: {
						name: '放空电压',
						key: 'capacity_voltage_setting_empty_voltage',
						byte: 2,
						unit: 'mV',
						index: 3,
						index_next: 4,
					},
					4: {
						name: '系统功耗',
						key: 'initialize_system_consumption',
						byte: 2,
						unit: 'mA',
						index: 4,
						index_next: 5,
					},
					5: {
						name: '生产日期',
						key: 'information_productionDate',
						byte: 2,
						value_type: 'produce_date',
						index: 5,
						index_next: 6,
					},
					6: {
						name: '序号',
						key: 'information_serialNumber',
						byte: 2,
						index: 6,
						index_next: 7,
					},
					7: {
						name: '循环次数',
						key: 'system_setting_cycle_count',
						byte: 2,
						index: 7,
						index_next: 8,
					},
					8: {
						name: '充电高温保护',
						key: 'temperature_setting_charge_high_temperature_protection',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 8,
						index_next: 9,
					},
					9: {
						name: '充电高温释放',
						key: 'temperature_setting_charge_high_temperature_recovery',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 9,
						index_next: 10,
					},
					10: {
						name: '充电低温保护',
						key: 'temperature_setting_charge_low_temperature_protection',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 10,
						index_next: 11,
					},
					11: {
						name: '充电低温释放',
						key: 'temperature_setting_charge_low_temperature_recovery',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 11,
						index_next: 12,
					},
					12: {
						name: '放电高温保护',
						key: 'temperature_setting_discharge_high_temperature_protection',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 12,
						index_next: 13,
					},
					13: {
						name: '放电高温释放',
						key: 'temperature_setting_discharge_high_temperature_recovery',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 13,
						index_next: 14,
					},
					14: {
						name: '放电低温保护',
						key: 'temperature_setting_discharge_low_temperature_protection',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 14,
						index_next: 15,
					},
					15: {
						name: '放电低温释放',
						key: 'temperature_setting_discharge_low_temperature_recovery',
						byte: 2,
						unit: '°C',
						value_type: 'is_temperature',
						index: 15,
						index_next: 16,
					},
					16: {
						name: '总压过压保护',
						key: 'protection_parameters_total_overvoltage_protection',
						byte: 2,
						unit: 'mV',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 16,
						index_next: 17,
					},
					17: {
						name: '总压过压释放',
						key: 'protection_parameters_total_overvoltage_recovery',
						byte: 2,
						unit: 'mV',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 17,
						index_next: 18,
					},
					18: {
						name: '总压欠压保护',
						key: 'protection_parameters_total_undervoltage_protection',
						byte: 2,
						unit: 'mV',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 18,
						index_next: 19,
					},
					19: {
						name: '总压欠压释放',
						key: 'protection_parameters_total_undervoltage_recovery',
						byte: 2,
						unit: 'mV',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 19,
						index_next: 20,
					},
					20: {
						name: '单体过压保护',
						key: 'protection_parameters_overvoltage_protection',
						byte: 2,
						unit: 'mV',
						index: 20,
						index_next: 21,
					},
					21: {
						name: '单体过压释放',
						key: 'protection_parameters_overvoltage_recovery',
						byte: 2,
						unit: 'mV',
						index: 21,
						index_next: 22,
					},
					22: {
						name: '单体欠压保护',
						key: 'protection_parameters_undervoltage_protection',
						byte: 2,
						unit: 'mV',
						index: 22,
						index_next: 23,
					},
					23: {
						name: '单体欠压释放',
						key: 'protection_parameters_undervoltage_recovery',
						byte: 2,
						unit: 'mV',
						index: 23,
						index_next: 24,
					},
					24: {
						name: '充电过流保护',
						key: 'current_setting_charge_overcurrent_protection',
						byte: 2,
						unit: 'mA',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 24,
						index_next: 25,
					},
					25: {
						name: '放电过流保护',
						key: 'current_setting_discharge_overcurrent_protection',
						byte: 2,
						value_type: 'is_current',
						unit: 'mA',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 25,
						index_next: 26,
					},
					26: {
						name: '均衡电压',
						key: 'balanced_setting_balance_voltage',
						byte: 2,
						unit: 'mV',
						index: 26,
						index_next: 27,
					},
					27: {
						name: '均衡精度',
						key: 'balanced_setting_balance_accuracy',
						byte: 2,
						unit: 'mV',
						index: 27,
						index_next: 28,
					},
					28: {
						name: '检流阻值',
						key: 'system_setting_current_limit',
						byte: 2,
						unit: 'mR',
						index: 28,
						index_next: 29,
						value_type: 'get_mr',
					},
					29: {
						name: '开启均衡',
						key: 'balanced_setting_enable_balance',
						byte: 2,
						index: 29,
						index_next: 30,
						value_config: [
							'function_setting_switch',
							'function_setting_load_detection',
							'function_setting_balance',
							'function_setting_balance_mode',
							'function_setting_led',
							'function_setting_led_quantity',
							'function_setting_rtc',
							'function_setting_fcc_limit',
							'function_setting_handshake_enable',
							'function_setting_gps',
							'function_setting_buzzer_enable',
							'function_setting_battery_mode',
							'function_setting_current_capacity',
							'',
							'',
							'',
						],
						value_type: 'binary_system',
					},
					30: {
						name: '温度探头配置',
						key: 'temperature_probe_configuration',
						byte: 2,
						index: 30,
						index_next: 31,
						value_config: [
							'function_setting_temp_1',
							'function_setting_temp_2',
							'function_setting_temp_3',
							'function_setting_temp_4',
							'function_setting_temp_5',
							'function_setting_temp_6',
							'function_setting_temp_7',
							'function_setting_temp_8',
						],
						value_type: 'binary_system',
					},
					31: {
						name: '串数',
						key: 'initialize_series_number',
						byte: 2,
						index: 31,
						index_next: 32,
					},
					32: {
						name: '开关控制时间',
						key: 'switch_control_time',
						byte: 2,
						unit: 's',
						index: 32,
						index_next: 33,
					},
					33: {
						name: 'LED工作时间',
						key: 'led_working_time',
						byte: 2,
						unit: 's',
						index: 33,
						index_next: 34,
					},
					34: {
						name: '80%',
						key: 'capacity_voltage_setting_80_percent',
						byte: 2,
						unit: 'mV',
						index: 34,
						index_next: 35,
					},
					35: {
						name: '60%',
						key: 'capacity_voltage_setting_60_percent',
						byte: 2,
						unit: 'mV',
						index: 35,
						index_next: 36,
					},
					36: {
						name: '40%',
						key: 'capacity_voltage_setting_40_percent',
						byte: 2,
						unit: 'mV',
						index: 36,
						index_next: 37,
					},
					37: {
						name: '20%',
						key: 'capacity_voltage_setting_20_percent',
						byte: 2,
						unit: 'mV',
						index: 37,
						index_next: 38,
					},
					38: {
						name: '硬件过压保护值',
						key: 'hardware_overvoltage_protection_value',
						byte: 2,
						unit: 'mV',
						index: 38,
						index_next: 39,
					},
					39: {
						name: '硬件欠压保护值',
						key: 'hardware_undervoltage_protection_value',
						byte: 2,
						unit: 'mV',
						index: 39,
						index_next: 40,
					},
					40: {
						name: '二级过流保护设置',
						key: 'current_setting_secondary_overcurrent_setting',
						byte: 2,
						unit: 'ms',
						index: 40,
						index_next: 41,
						value_type: 'low4_high4',
						form_data_name: 'current_setting_secondary_overcurrent_protection',
						form_time_name: 'current_setting_secondary_overcurrent_delay',
					},
					41: {
						name: '短路保护设置',
						key: 'current_setting_short_circuit_setting',
						byte: 2,
						unit: 'uS',
						index: 41,
						index_next: 42,
						value_type: 'low4_high4',
						form_data_name: 'current_setting_short_circuit_protection',
						form_time_name: 'current_setting_short_circuit_delay',
					},
					42: {
						name: '硬件过欠压延时',
						key: 'hardware_over_undervoltage_delay',
						byte: 2,
						unit: 's',
						index: 42,
						index_next: 43,
					},
					43: {
						name: '短路保护恢复延时',
						key: 'current_setting_short_circuit_recovery_delay',
						byte: 2,
						unit: 's',
						index: 43,
						index_next: 44,
					},
					44: {
						name: '充电低温延时',
						key: 'temperature_setting_charge_low_temperature_delay',
						byte: 2,
						unit: 's',
						index: 44,
						index_next: 45,
					},
					45: {
						name: '充电高温延时',
						key: 'temperature_setting_charge_high_temperature_delay',
						byte: 2,
						unit: 's',
						index: 45,
						index_next: 46,
					},
					46: {
						name: '放电低温延时',
						key: 'temperature_setting_discharge_low_temperature_delay',
						byte: 2,
						unit: 's',
						index: 46,
						index_next: 47,
					},
					47: {
						name: '放电高温延时',
						key: 'temperature_setting_discharge_high_temperature_delay',
						byte: 2,
						unit: 's',
						index: 47,
						index_next: 48,
					},
					48: {
						name: '总压欠压延时',
						key: 'protection_parameters_total_undervoltage_delay',
						byte: 2,
						unit: 's',
						index: 48,
						index_next: 49,
					},
					49: {
						name: '总压过压延时',
						key: 'protection_parameters_total_overvoltage_delay',
						byte: 2,
						unit: 's',
						index: 49,
						index_next: 50,
					},
					50: {
						name: '单体欠压延时',
						key: 'protection_parameters_undervoltage_delay',
						byte: 2,
						unit: 's',
						index: 50,
						index_next: 51,
					},
					51: {
						name: '单体过压延时',
						key: 'protection_parameters_overvoltage_delay',
						byte: 2,
						unit: 's',
						index: 51,
						index_next: 52,
					},
					52: {
						name: '充电过流延时',
						key: 'current_setting_charge_overcurrent_delay',
						byte: 2,
						unit: 's',
						index: 52,
						index_next: 53,
					},
					53: {
						name: '充电过流恢复延时',
						key: 'current_setting_charge_overcurrent_recovery_delay',
						byte: 2,
						unit: 's',
						index: 53,
						index_next: 54,
					},
					54: {
						name: '放电过流延时',
						key: 'current_setting_discharge_overcurrent_delay',
						byte: 2,
						unit: 's',
						index: 54,
						index_next: 55,
					},
					55: {
						name: '放电过流恢复延时',
						key: 'current_setting_discharge_overcurrent_recovery_delay',
						byte: 2,
						unit: 's',
						index: 55,
						index_next: 56,
					},
					56: {
						name: '电池生产商',
						key: 'information_batteryManufacturer',
						byte: 32,
						value_type: 'ascii',
						index: 56,
						index_next: 72,
					},
					72: {
						name: 'BMS-编码信息',
						key: 'bms_encoding_information',
						byte: 32,
						value_type: 'ascii',
						index: 72,
						index_next: 88,
					},
					88: {
						name: '条码',
						key: 'information_barcode',
						byte: 32,
						value_type: 'ascii',
						index: 88,
						index_next: 104,
					},
					104: {
						name: 'GPS关断电压',
						key: 'gps_shutdown_voltage',
						byte: 2,
						unit: 'mV',
						index: 104,
						index_next: 105,
					},
					105: {
						name: 'GPS关断延时',
						key: 'gps_shutdown_delay',
						byte: 2,
						unit: 's',
						index: 105,
						index_next: 106,
					},
					106: {
						name: '90%',
						key: 'capacity_voltage_setting_90_percent',
						byte: 2,
						unit: 'mV',
						index: 106,
						index_next: 107,
					},
					107: {
						name: '70%',
						key: 'capacity_voltage_setting_70_percent',
						byte: 2,
						unit: 'mV',
						index: 107,
						index_next: 108,
					},
					108: {
						name: '50%',
						key: 'capacity_voltage_setting_50_percent',
						byte: 2,
						unit: 'mV',
						index: 108,
						index_next: 109,
					},
					109: {
						name: '30%',
						key: 'capacity_voltage_setting_30_percent',
						byte: 2,
						unit: 'mV',
						index: 109,
						index_next: 110,
					},
					110: {
						name: '10%',
						key: 'capacity_voltage_setting_10_percent',
						byte: 2,
						unit: 'mV',
						index: 110,
						index_next: 111,
					},
					111: {
						name: '100%',
						key: 'capacity_voltage_setting_100_percent',
						byte: 2,
						unit: 'mV',
						index: 111,
						index_next: 112,
					},
					112: {
						name: '学习容量',
						key: 'learning_capacity',
						byte: 2,
						unit: 'mAh',
						unit_read_compute: 0.01,
						unit_read_conversion: 1000,
						index: 112,
						index_next: 113,
					},
					113: {
						name: '容量修正间隔',
						key: 'system_setting_capacity_correction_interval',
						byte: 2,
						unit: 's',
						index: 113,
						index_next: 114,
					},
					114: {
						name: '额定电压',
						key: 'BatteryVoltage',
						byte: 2,
						unit: 'mAV',
						unit_read_compute: 0.1,
						unit_read_conversion: 1000,
						index: 114,
						index_next: 115,
						update_form: true,
					},
					115: {
						name: '额定电流',
						key: 'rated_current',
						byte: 2,
						unit: 'A',
						index: 115,
						index_next: 116,
					},
					116: {
						name: '最大功率',
						key: 'maximum_power',
						byte: 2,
						unit: 'W',
						index: 116,
						index_next: 117,
					},
					117: {
						name: '额定充电电压',
						key: 'rated_charging_voltage',
						byte: 2,
						unit: 'mAV',
						unit_read_compute: 0.1,
						unit_read_conversion: 1000,
						index: 117,
						index_next: 118,
					},
					118: {
						name: '额定放电电流',
						key: 'information_ratedDischargeCurrent',
						byte: 2,
						unit: 'A',
						index: 118,
						index_next: 119,
					},
					119: {
						name: '额定充电电流',
						key: 'information_ratedChargeCurrent',
						byte: 2,
						unit: 'A',
						index: 119,
						index_next: 120,
					},
					120: {
						name: '额定放电功率',
						key: 'rated_discharge_power',
						byte: 2,
						unit: 'W',
						index: 120,
						index_next: 121,
					},
					121: {
						name: '识别电流',
						key: 'system_setting_recognition_current',
						byte: 2,
						unit: 'mA',
						index: 121,
						index_next: 122,
					},
					122: {
						name: '休眠时间',
						key: 'system_setting_sleep_time',
						byte: 2,
						unit: 'mA',
						index: 122,
						index_next: 123,
					},
					123: {
						name: '预留告警参数',
						key: 'reserve_alarm_parameters',
						byte: 70,
						index: 123,
						index_next: 158,
					},
					158: {
						name: '电池型号',
						key: 'information_batteryModel',
						byte: 24,
						value_type: 'ascii',
						index: 158,
						index_next: 170,
					},
					170: {
						name: 'BMS地址',
						key: 'information_bmsAddress',
						byte: 12,
						value_type: 'information_bmsAddress',
						index: 170,
						index_next: 176,
					},
					176: {
						name: 'BMS型号',
						key: 'information_bmsModel',
						byte: 16,
						value_type: 'ascii',
						index: 176,
						index_next: 184,
					},
				},
			},
			251: {
				// 0xFB
				tips: '控制MOS成功返回',
			},
		};

		if (!_this.objJudge(config[cmd])) {
			// 电压校准返回的cmd是对应某一串的特有的cmd
			if (_this.BLUETOOTH_DEVICE_CONFIG.bluetooth_connect) {
				_this.responseInstruct(cmd);
				console.log('无指令配置');
			}
			return;
		}

		/*
            读03指令是基本信息及状态，包含容量，总压、电流、温度、保护状态等芯片
            读04指令是对应电池的电压集合 -- 单个数组 []
            读05保护板硬件版本号 - 读取板子的版本信息
            读AA保护板历史保护次数 – 读取历史的保护次数

            读FA根据序号读取参数

        */
		if (cmd == 0x00) {
			// page_buffer长度等于0是进入工厂模式
			// page_buffer长度大于0则是读取芯片类型
			if (_this.objJudge(page_buffer)) {
				let _value = _this.arr_handle_value(page_buffer, 'default');
				_this.update_bluetooth_fun({
					bluetooth_deviceId,
					update: { bluetooth_chip_type: _value },
				});
				_this.store_set_state_config({ state_name: 'BLUETOOTH_INIT_FORM', data: { bluetooth_chip_type: _value } });

				_this.update_pagedevice();
				// console.log('读取芯片类型');
				_this.responseInstruct(cmd, _echo);
				return;
			}
		} else if (cmd == 0x04) {
			// 04指令对应电池的电压集合 -- 单个数组 index_voltage_chart index_voltage_chart_config
			let voltage_list = [];
			let max = 0;
			let min = 0;
			// 如果page_buffer长度为24 则有12串电压 n为高低位得出的电压值
			// console.log(page_buffer);
			_this.split_arr_number(page_buffer, 2).forEach((item, index) => {
				let n = _this.highlow_to_num(item[0], item[1]);

				// let is_normal_user = uni.getStorageSync('is_normal_user');
				// if (is_normal_user) {
				//     n = _this.roundDownToNearestTen(n, 2)
				// }
				if (index == 0) {
					max = n;
					min = n;
				}

				if (n > max) {
					max = n;
				}

				if (n < min) {
					min = n;
				}
				let key_name = `voltage_calibration_${index + 1}`;
				INIT_FORM[key_name] = n;
				_echo.push({
					key: key_name,
					value: n,
				});

				// _alldata.push({
				// 	key: key_name,
				// 	value: n,
				// });

				voltage_list.push(n);

				// return n
			});

			let diff = max - min;

			let avg = voltage_list.reduce((p, n, i) => {
				let t = p + n;
				if (i == voltage_list.length - 1) {
					return _this.back_number(t / voltage_list.length, 0);
				} else {
					return t;
				}
			}, 0);

			let max_index = voltage_list.findIndex(item => item == max);
			let min_index = voltage_list.findIndex(item => item == min);
			Object.assign(INIT_FORM, {
				dev_max: max,
				dev_min: min,
				dev_avg: avg,
				dev_diff: diff,
				index_voltage_chart: voltage_list,
				index_voltage_chart_config: {
					max,
					min,
					diff,
					max_index,
					min_index,
				},
			});
		} else if (cmd == 0x0a) {
			if (page_buffer[0] == 17) {
				// 0x11 充电模式
				Object.assign(INIT_FORM, { battery_charge_mode: page_buffer[1] });
			}
			// console.log(page_buffer, '0x0a');
		} else if (cmd == 0xaa) {
			//  读AA保护板历史保护次数 – 读取历史的保护次数

			let protection_count = [
				'dev_preserve',
				'protection_count_charge_overcurrent',
				'protection_count_discharge_overcurrent',
				'protection_count_single_overvoltage',
				'protection_count_single_undervoltage',
				'protection_count_charge_high_temperature',
				'protection_count_charge_low_temperature',
				'protection_count_discharge_high_temperature',
				'protection_count_discharge_low_temperature',
				'protection_count_total_overvoltage',
				'protection_count_total_undervoltage',
				'dev_restart',
			];

			let _0xAA_obj = {};
			_this.split_arr_number(page_buffer, 2).forEach((item, index) => {
				let n = _this.highlow_to_num(item[0], item[1]);
				_this.$set(_0xAA_obj, protection_count[index], n);
				_echo.push(n);
				// _alldata.push({
				// 	key: protection_count[index],
				// 	value: n,
				// });
			});
			// 更新到缓存 设置页面的保护次数用到
			Object.assign(INIT_FORM, _0xAA_obj);
			// 更新到实时页面，上传保护信息用到
		} else if (cmd == 0xf6) {
			// 电池内阻
			let _0xF6_obj = {};
			_this.split_arr_number(page_buffer, 2).forEach((_parameter, index) => {
				let n = _this.arr_handle_value(_parameter, 'resistance');
				// let n = _this.arr_handle_value([0xff, 0xfb], 'resistance');
				let key = `link_resistance_${index + 1}`;
				_this.$set(_0xF6_obj, key, n);
				_echo.push({
					key,
					value: n,
				});

				// _alldata.push({
				// 	key,
				// 	value: n,
				// });
			});
			// 更新到缓存 设置页面的保护次数用到
			Object.assign(INIT_FORM, _0xF6_obj);
		} else if (cmd == 0xfa) {
			if (_this.objJudge(page_buffer)) {
				// 根据序号读取参数
				// 开始序号
				let _no = _this.highlow_to_num(page_buffer[0], page_buffer[1]);
				// 从那个参数开始
				// let parameter_start = _no;
				// 读取多少个参数
				// let parameter_total = page_buffer[2];
				let _stop_index = _this.deepclone(_no) + page_buffer[2];

				let parameter_arr = page_buffer.slice(3);

				let _config = config[cmd].config_list || {};

				let start_slice = 0;

				while (_no >= 0) {
					let _item = _config[_no];
					if (_stop_index == _item.index_next) {
						// 比方 [0, 104, 16] 从104开始查后续16个 结束应该是119
						// parameter_start 104
						// parameter_total 16

						// 结束的索引应该是120
						// 到最后一项了
						_no = -1;
					} else {
						_no = _item.index_next;
					}
					let end_slice = start_slice + _item.byte;
					// model

					let model = 'default';
					if (_this.objJudge(_item.value_type)) {
						model = _item.value_type;
					}
					let _parameter = parameter_arr.slice(start_slice, end_slice);
					let _value = _this.arr_handle_value(_parameter, model, _item);

					if (_this.gettype(_value) == 'Number') {
						if (_this.objJudge(_item.unit_read_compute)) {
							// 单位计算
							_value *= _item.unit_read_compute;
						}

						if (_this.objJudge(_item.unit_read_conversion)) {
							// 精度转换 A转 mA 就会乘 1000
							_value *= _item.unit_read_conversion;
						}

						_value = _this.back_number(_value);
					}

					// if (_item.key == 'balanced_setting_enable_balance') {
					// 功能配置 balanced_setting_enable_balance
					// 温度探头配置 temperature_probe_configuration
					let value_config_fun_back = _this.com_value_config_init(_item, _value);
					if (_this.objJudge(value_config_fun_back)) {
						// 功能配置 温度探头配置按钮列表初始化
						Object.assign(INIT_FORM, value_config_fun_back);
					}

					// }

					_echo.push({
						key: _item.key,
						value: _value,
						parameter: _parameter,
						name: _item.name,
						_item,
					});

					// _alldata.push({
					// 	key: _item.key,
					// 	name: _item.name,
					// 	value: _value,
					// });

					switch (_this.gettype(_value)) {
						case 'Object':
							// 二级过流保护及延时设置
							for (const v_k in _value) {
								INIT_FORM[v_k] = _value[v_k];
							}
							break;
						default:
							INIT_FORM[_item.key] = _value;
							break;
					}

					// if (parameter_arr.length == end_slice) {
					start_slice += _item.byte;
					// }
				}
			}
		} else {
			let config_list = config[cmd].config_list || [];
			if (_this.objJudge(config[cmd].config_list)) {
				// 03指令独有的温度显示 [mos、nct * n个、湿度]
				let index_temperature = [];
				let _0x03_obj = {};
				// INIT_FORM[_item.key] = _value;
				config_list.reduce((_p, _now, i) => {
					let start = _p.index_end || 0;
					let end = _now.byte + start;
					let has_list = _this.objJudge(_p.byte_list);
					if (has_list) {
						// 例如 上一个_p是NCT个数为3 后续的就有 3 * _now.byte 6位数据对应 3个NCT
						// _p.byte_list ${布尔值} 后续是否有子项list
						// _p.value 有多少NTC个
						//  所以结束索引需要 _p.value * _now.byte 多少个 * 自身大小
						end = _now.byte * _p.value + start;
					}
					_now['_item'] = _this.deepclone(_now);
					_now['index_start'] = start;
					_now['index_end'] = end;
					_now['index'] = i;
					_now['_parameter'] = page_buffer.slice(start, end);

					if (has_list) {
						_now['value'] = _now._parameter;
					} else if (_now.byte == 1) {
						_now['value'] = _now._parameter[0];
					} else if (_now.byte == 2) {
						_now['value'] = _this.highlow_to_num(_now._parameter[0], _now._parameter[1]);
					}

					if (_now.value_type) {
						_now['value'] = _this.arr_handle_value(_now['_parameter'], _now.value_type);
					}

					_echo.push(_now);

					// _alldata.push({
					// 	key: _now.key,
					// 	value: _now.value,
					// 	name: _now.name,
					// });

					_0x03_obj[_now.key] = _now['value'];

					if (_now.key == 'BatteryCapacity') {
						_0x03_obj[_now.key] = _now['value'] * 10;
					}

					if (_now.key == 'index_protection_status') {
						let switch_status = _now['value'].indexOf(1) > -1 ? 1 : 0;
						_0x03_obj[`${_now.key}_switch`] = switch_status;
					}
					if (_now.key == 'index_balance_status') {
						let switch_status = _now['value'].indexOf(1) > -1 ? 1 : 0;
						_0x03_obj[`${_now.key}_switch`] = switch_status;
					}
					// if (_now.key == 'index_software_version') {
					// 	// 软件版本
					//     INIT_FORM['index_software_version'] = _now['value'];
					//     _0x03_obj[`${_now.key}_switch`] = switch_status;
					// }

					// -------------------------------------- MOS显示 充电开关放电开关 start

					// 二进制数组 [0, 1, 0, 0, 0, 0, 0, 0] 与 以下数组匹配
					// ["index_charge_switch", "index_discharge_switch", "current_limiting_switch", "heat_switch", "", "", "", "current_capacity_unit"]
					// 充电开关放电开关
					if (_this.objJudge(_now.form_config)) {
						_now['form_config'].forEach((item, index) => {
							if (_this.objJudge(item)) {
								// INIT_FORM[item] = _now['value'][index];
								_0x03_obj[item] = _now['value'][index];
							}
						});
					}
					// -------------------------------------- MOS显示 充电开关放电开关 end

					// -------------------------------------- 告警保护状态 start
					// 为长度16 或者 8的bit 二进制数组添加对标的文字状态数组
					// 告警保护提示中文用
					if (_this.objJudge(_now.value_config_tips)) {
						// 保护状态 index_protection_status
						// 告警状态 index_alarm_status

						let _show = [];
						let _list = [];

						_now['value'].forEach((item, index) => {
							if (item == 1) {
								let _s = {
									title: _now.value_config_tips[index],
									time: _this.happenTimeFun(new Date().getTime(), 'y-m-d h:i:s'),
								};
								_list.push(_now.value_config_tips[index]);
								_show.push(_s);
							}
						});

						// 对应配置初始化
						_0x03_obj[`${_now.key}_config`] = _now['value_config_tips'];
						// // 传给后台接口的数组
						_0x03_obj[`${_now.key}_list`] = _list;
						// 页面展示使用带有时间戳的数组
						_0x03_obj[`${_now.key}_show`] = _show;
					}
					// -------------------------------------- 告警保护状态 end

					// -------------------------------------- 温度 start

					// index_temperature 首页温度集合 [mos、nct * n个、湿度]
					let index_temperature_key = ['index_NTC_content', 'dev_humidity'];
					if (index_temperature_key.indexOf(_now.key) > -1) {
						if (_this.gettype(_now.value) == 'Array') {
							// mos是nct第一个温度
							index_temperature.push(...[_now.value[0], ..._now.value]);
						} else {
							index_temperature.push(_now.value);
						}
					}

					// -------------------------------------- 温度 end
					return _now;
				}, {});

				// -------------------------------------- 实时页面 功率 start
				if (_this.objJudge(_this.BLUETOOTH_INIT_FORM.dev_voltage)) {
					// 功率 = 电压 * 电流
					let index_power = _this.BLUETOOTH_INIT_FORM.dev_voltage * _this.BLUETOOTH_INIT_FORM.dev_current * 0.01;
					_0x03_obj[`index_power`] = index_power;
					// _this.BLUETOOTH_INIT_FORM.dev_current = 500;
					// 预计充满时间
					if (_this.BLUETOOTH_INIT_FORM.dev_current > 0) {
						let need_current = _this.BLUETOOTH_INIT_FORM.index_full_charge_capacity - _this.BLUETOOTH_INIT_FORM.dev_capacity;
						let need_current_time = (need_current / _this.BLUETOOTH_INIT_FORM.dev_current) * 3600000;
						let show = _this.timestamp_show_fun(need_current_time, 2);
						if (need_current_time > 0) {
							// _this.$set(_this.BLUETOOTH_INIT_FORM, 'index_full_time', show);
							_0x03_obj[`index_full_time`] = show;
						}
					}

					// 预计放空时间
					if (_this.BLUETOOTH_INIT_FORM.dev_current < 0) {
						let empty_time = _this.BLUETOOTH_INIT_FORM.dev_capacity;
						let need_empty_time = (empty_time / Math.abs(_this.BLUETOOTH_INIT_FORM.dev_current)) * 3600000;
						let show = _this.timestamp_show_fun(need_empty_time, 2);
						if (need_empty_time > 0) {
							// _this.$set(_this.BLUETOOTH_INIT_FORM, 'index_empty_time', show);
							_0x03_obj[`index_empty_time`] = show;
						}
					}
				}
				// -------------------------------------- 实时页面 功率 end

				// -------------------------------------- 页面温度配置 start
				if (_this.objJudge(index_temperature)) {
					let index_temperature_show = [];
					let ntc_index = 1;
					index_temperature.forEach((v, i) => {
						let back_v = {
							title: '',
							value: '',
						};
						if (i == 0) {
							back_v.title = 'MOS';
						} else if (i == index_temperature.length - 1) {
							back_v.title = '湿度';
						} else {
							back_v.title = `NTC${ntc_index}`;
							ntc_index++;
						}
						back_v.value = (v * 0.1).toFixed(1) + ' °C';
						index_temperature_show.push(back_v);
					});
					_0x03_obj[`dev_temp`] = index_temperature[0];
					_0x03_obj[`dev_humidity`] = index_temperature[index_temperature.length - 1];
					_0x03_obj[`index_temperature_show`] = index_temperature_show;
				}
				// -------------------------------------- 页面温度配置 start
				Object.assign(INIT_FORM, _0x03_obj);
			}
		}

		// uni.setStorageSync('cache_form', INIT_FORM);

		if (_this.objJudge(INIT_FORM)) {
			_this.store_set_state_config({ state_name: 'BLUETOOTH_INIT_FORM', data: INIT_FORM });
		}
		// console.log(INIT_FORM, 'INIT_FORM');
		// console.log(JSON.stringify(_this.BLUETOOTH_INIT_FORM));

		if (_this.show_buffer) {
			console.log(_echo, '_echo');
		}
		// _this.BLUETOOTH_ALL_DATA.forEach(v => {
		// 	let value_t = _this.gettype(v.value);
		// 	if (value_t == 'String') {
		// 	} else if (value_t == 'Number') {
		// 	} else {
		// 		console.log(v);
		// 		v['check'] = true;
		// 	}
		// });

		// console.log(`${_this.tts(cmd)}指令分发到页面数据`)
		// console.log(`${_this.page_name}是页面名字`)

		// console.log('正常响应');
		_this.responseInstruct(cmd, _echo);
		// console.log(cmd, config[cmd]['tips']);
		if (cmd == 0x03) {
			// 检查如果有告警或者保护 上传信息到后台接口
			_this.com_update_warn();
		}
	},

	// value_config初始话
	// 更新到页面
	com_value_config_init(_item, _value) {
		let _this = this;
		let _back = {};
		// 功能配置 balanced_setting_enable_balance
		// 温度探头配置 temperature_probe_configuration

		if (_this.objJudge(_item.value_config)) {
			_value.forEach((vv, index) => {
				if (_this.objJudge(_item.value_config[index])) {
					_back[_item.value_config[index]] = vv;
				}
				if (_item.value_config[index] == 'function_setting_balance_mode') {
					// 均衡方式 充电均衡1 静态均衡0
					let cache_config = uni.getStorageSync('cache_config') || {};
					cache_config[_item.value_config[index]] = {
						select_index: vv,
						select_list: [
							{
								key: 0,
								title: '静态均衡',
							},
							{
								key: 1,
								title: '充电均衡',
							},
						],
					};
					uni.setStorageSync('cache_config', cache_config);
				}
			});
		}

		return _back;
	},

	// 1820 -> 1800 (1820,2)
	roundDownToNearestTen(num, digits) {
		// 将数字转换为字符串
		var numStr = num.toString();

		// 计算需要向下取整的位数
		var roundDigits = Math.max(0, numStr.length - digits);

		// 取得数字的前roundDigits位
		var prefix = numStr.substring(0, roundDigits);

		// 取得需要向下取整的部分
		var roundPart = parseInt(numStr.substring(roundDigits));

		// 向下取整到最接近的十的倍数
		var roundedDown = Math.floor(roundPart / 10) * 10;

		// 构造新的数字字符串
		var newNumStr = prefix + roundedDown.toString().padStart(digits - roundDigits, '0');

		// 将新的数字字符串转换为整数
		var newNum = parseInt(newNumStr);

		return newNum;
	},
	// 触发了告警或者保护需要向接口上传数据
	com_update_warn() {
		let _this = this;
		if (!_this.judge_bluetooth()) return;
		// 保护状态 index_protection_status
		// 告警状态 index_alarm_status
		let wran = [
			{
				wran_type: 1,
				wran_key: 'index_protection_status_list',
			},
			{
				wran_type: 2,
				wran_key: 'index_alarm_status_list',
			},
		];
		wran.forEach(item => {
			let _list = _this.BLUETOOTH_INIT_FORM[item.wran_key];
			if (_this.objJudge(_list)) {
				let data = {
					dev_id: _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_device_mac,
					warn_type: item.wran_type,
					warn_msg: _list.join(','),
				};
				let url = '/bms/warn';
				// console.log(_list, data)
				_this.com_getdata({
					url,
					data,
					data_fun: function (v) {
						console.log(v, data, `保护告警信息传输-${url}成功`);
					},
				});
			}
		});
	},

	// 十六进制数据后续处理
	binary_system_fun(arr, item) {
		// debugger
	},

	// 二级过流保护设置 / 短路保护设置初始化列表
	overcurrent_short_fun(hl, item) {
		let _this = this;
		let { h, l } = hl;
		let { key: setting_name, form_data_name, form_time_name } = item;

		let init_cache = uni.getStorageSync('cache_form') || {};
		let cache_config = uni.getStorageSync('cache_config') || {};
		let fun_data = {};

		// 检流阻值
		let _mr = init_cache['system_setting_current_limit'] || uni.getStorageSync('system_setting_current_limit') || 0.1;

		// 芯片类型
		let chip_type = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_chip_type || 0;
		// 对应的值和延时时间也有不同的取值
		//  0 T1方案
		//  1 凹凸7712
		//  2 新塘松下49522
		//  3 中颖309
		//  4 中颖303
		//  5 集澈DC10XX
		//  6 OZ3714
		let config = {
			current_setting_secondary_overcurrent_setting: {
				unit_config: {
					h: 'A',
					l: 'mS',
				},
				chip_config: {
					0: [
						{
							hl_key: 'h',
							_table: [8, 11, 14, 17, 19, 22, 25, 28, 31, 33, 36, 39, 42, 44, 47, 50],
							_table_rsns: [17, 22, 28, 33, 39, 44, 50, 56, 61, 67, 72, 78, 83, 89, 94, 100],
						},
						{
							hl_key: 'l',
							_table: [8, 20, 40, 80, 160, 320, 640, 1280],
						},
					],
					1: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
							_table: [500, 1000, 1500, 2000],
						},
					],
					2: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
					3: [
						{
							hl_key: 'h',
							_table: [20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 160, 180, 200],
						},
						{
							hl_key: 'l',
							_table: [50, 100, 200, 400, 600, 800, 1000, 2000, 4000, 6000, 8000, 10000, 15000, 20000, 30000, 40000],
						},
					],
					// 4 中颖303没有过流
					4: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
					5: [
						{
							hl_key: 'h',
							_table: [4, 10, 16, 21, 28, 33, 38, 44, 50, 55, 61, 67, 73, 78, 84, 90],
						},
						{
							hl_key: 'l',
							_table: [32, 80, 160, 320, 640, 1280, 2560, 5120],
						},
					],

					6: [
						{
							hl_key: 'h',
							_table: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160],
						},
						{
							hl_key: 'l',
							_table: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32],
						},
					],
					254: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
				},
			},
			current_setting_short_circuit_setting: {
				unit_config: {
					h: 'A',
					l: 'uS',
				},
				chip_config: {
					0: [
						{
							hl_key: 'h',
							_table: [22, 33, 44, 56, 67, 78, 89, 100],
							_table_rsns: [44, 67, 89, 111, 133, 155, 178, 200],
						},
						{
							hl_key: 'l',
							_table: [70, 100, 200, 400],
						},
					],
					1: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
					2: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
					3: [
						{
							hl_key: 'h',
							_table: [50, 80, 140, 170, 200, 230, 260, 290, 320, 350, 400, 500, 600, 800, 1000],
						},
						{
							hl_key: 'l',
						},
					],

					4: [
						{
							hl_key: 'h',
							_table: [100, 200, 300, 400],
						},
						{
							hl_key: 'l',
							_table: [50, 100, 300, 500],
						},
					],

					5: [
						{
							hl_key: 'h',
							_table: [19, 30, 41, 53, 64, 75, 87, 98, 110, 120, 132, 143, 155, 166, 177, 190],
						},
						{
							hl_key: 'l',
							_table: [560, 800, 1600, 3200],
						},
					],

					6: [
						{
							hl_key: 'h',
							_table: [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600, 640],
						},
						{
							hl_key: 'l',
						},
					],

					254: [
						{
							hl_key: 'h',
						},
						{
							hl_key: 'l',
						},
					],
				},
			},
		};
		let current_config = config[setting_name].chip_config[chip_type];
		let unit_config = config[setting_name].unit_config;
		if (_this.objJudge(current_config)) {
			current_config.forEach(config_item => {
				let h_or_l = hl[config_item.hl_key];
				let fun_type = config_item.hl_key == 'h' ? 'form_data_name' : 'form_time_name';
				if (_this.objJudge(config_item.k)) {
					fun_type = config_item.k;
				}
				let _unit = unit_config[config_item.hl_key];
				if (_this.objJudge(config_item.unit)) {
					_unit = config_item.unit;
				}
				let _max = _this.objJudge(config_item.max_gear) ? config_item.max_gear : 16;
				let _table = _this.objJudge(config_item._table) ? config_item._table : [];
				if (chip_type == 0) {
					if (config_item.hl_key == 'h' && fun_type == 'form_data_name') {
						// 短路值或者过流值 二进制8位数组高位为1则是 RSNS:表示过流及短路值翻倍模式
						if (h_or_l >= 8) {
							// RSNS模式取 _table_rsns数组
							_table = _this.objJudge(config_item._table_rsns) ? config_item._table_rsns : [];
						}
					}
				}
				let form_v_name = item[fun_type];
				let { select_value, select_index, select_list } = _this.overcurrent_short_judge_fun({
					h_or_l,
					_unit,
					_max,
					_table,
					_mr,
					setting_name,
					chip_type,
					fun_type,
				});

				fun_data[form_v_name] = select_value;
				// fun_data.hl_arr = hl;
				cache_config[form_v_name] = {
					select_index,
					select_list,
				};
			});
		} else {
			console.log({
				chip_type,
			});
		}

		uni.setStorageSync('cache_config', cache_config);
		return fun_data;
	},
	overcurrent_short_judge_fun(config) {
		let { h_or_l, _unit, _max, _table, _mr, setting_name, chip_type, fun_type } = config;

		// console.log(config)
		let _this = this;
		let for_index = _max;
		if (_this.objJudge(_table)) {
			for_index = _table.length;
		}

		let select_value = 0,
			select_index = 0,
			select_list = [];

		if (setting_name == 'current_setting_secondary_overcurrent_setting') {
			for (let index = 0; index < for_index; index++) {
				let key = 0;
				if (fun_type == 'form_data_name') {
					switch (chip_type) {
						case 0:
							break;
						case 1:
							// 10*OCD_T+5
							key = (10 * index + 5) / _mr;
							break;
						case 2:
							// 20*OCD_T+5
							key = (20 * index + 5) / _mr;
							break;
						case 3:
							break;
						case 4:
							break;
						case 5:
							break;
						case 254:
							key = (12 * index + 20) / _mr;

							break;
					}

					if (_this.objJudge(_table)) {
						key = _table[index] / _mr;
					}
				} else if (fun_type == 'form_time_name') {
					switch (chip_type) {
						case 0:
							break;
						case 1:
							// 凹凸的延时只有4个档位 500 1000 1500 2000
							// key = (index + 1) * 500;
							break;
						case 2:
							key = 20 * index + 10;
							break;
						case 3:
							break;
						case 4:
							break;
						case 5:
							break;
						case 254:
							key = 32 * index + 2;
							break;
					}
					if (_this.objJudge(_table)) {
						key = _table[index];
					}
				}

				let title = `${key}${_unit}`;
				select_list.push({
					key,
					title,
				});
				if (index == h_or_l) {
					select_index = index;
					select_value = key;
				}
			}
		}

		if (setting_name == 'current_setting_short_circuit_setting') {
			for (let index = 0; index < for_index; index++) {
				// const element = array[index];
				let key = 0;
				// (10 * index + 5) / mr
				if (fun_type == 'form_data_name') {
					switch (chip_type) {
						case 0:
							break;
						case 1:
							//  20*SCD_T+20
							key = (20 * index + 20) / _mr;
							break;
						case 2:
							//  40*SCD_T+20
							key = (40 * index + 20) / _mr;
							break;
						case 3:
							break;
						case 4:
							break;
						case 5:
							break;
						case 6:
							break;
						case 254:
							key = (30 * index + 50) / _mr;
							break;
					}

					if (_this.objJudge(_table)) {
						key = _table[index] / _mr;
					}
				} else if (fun_type == 'form_time_name') {
					switch (chip_type) {
						case 0:
							break;
						case 1:
							//  62.5*SCD_D+62.5
							key = 62.5 * index + 62.5;

							break;
						case 2:
							//  62.5*SCD_D+31.25
							key = 62.5 * index + 31.25;
							break;
						case 3:
							//  64*SCD_D
							key = 62.5 * index;
							break;
						case 4:
							break;
						case 5:
							break;
						case 6:
							//  62.5*（i+1）
							key = 62.5 * (index + 1);
							break;

						case 254:
							key = 125 * index + 125;
							break;
					}
					if (_this.objJudge(_table)) {
						key = _table[index];
					}
				}

				let title = `${key}${_unit}`;
				select_list.push({
					key,
					title,
				});
				if (index == h_or_l) {
					select_index = index;
					select_value = key;
				}
			}
		}

		return {
			select_value,
			select_index,
			select_list,
		};
	},

	// 循环数据找到符合条件的项
	find_to_handle: function (e) {
		let _this = this;
		let { data, attr_name, find_fun } = e;
		if (!find_fun(e)) {
			if (_this.gettype(data) == 'Array') {
				for (let i = 0; i < data.length; i++) {
					_this.find_to_handle({
						data: data[i],
						find_fun,
						attr_name: false,
					});
				}
			} else if (_this.gettype(data) == 'Object') {
				for (let k in data) {
					// console.log(k, data[k])
					_this.find_to_handle({
						data: data[k],
						attr_name: k,
						find_fun,
					});
				}
			}
		}
	},

	// 指令返回的十进制数组根据不同类型处理成真实数据
	/**
     * 
     * @param {*} res_value 
     * @param {string} value_type 
     * // default 长度为2的 [高位,低位] 数组
       // ascii  [长度为xx的字符长度,ascii码1,ascii码2] 数组
       // current 电流
       // temperature 温度
     * @returns 
     */
	arr_handle_value(res_value, value_type, item = false) {
		let _this = this;
		let _v;
		switch (value_type) {
			case 'version':
				// 版本号 36 -> '3.6'
				_v = _this.tts(res_value[0], false);
				// _v = res_value[0].toString();
				// _v = res_value[0].toString();
				_v = `${_v.substr(0, 1)}.${_v.substr(1, 2)}`;
				break;
			case 'is_current':
				// 带符号型16进制数，通过电流判断电池充放电状态，充电为正，放电为负。例如充电1A，传输数值为0x0064,放电1A传输数值为0X10000 -0X0064 = 0Xff9c
				// [0,1] - 1  - fun
				_v = _this.highlow_to_num(res_value[0], res_value[1]);
				let current_arr = _this.sttwo(_v);
				if (current_arr[current_arr.length - 1] == 1) {
					// 最高位为1的话就是负数 放电 0X10000 = 65536
					_v = 0 - (65536 - _v);
				} else {
					// 最高位为0的话就是正数 充电
				}

				break;
			case 'resistance':
				// 连接内阻
				_v = _this.highlow_to_num(res_value[0], res_value[1]);
				let resistance_arr = _this.sttwo(_v);
				if (resistance_arr[resistance_arr.length - 1] == 1) {
					// 最高位为1的话就是负数 放电 0X10000 = 65536
					_v = 0 - (65536 - _v);
				} else {
					// 最高位为0的话就是正数 充电
				}
				let unit_read_compute = 0.1;
				_v = _this.back_number(_v * unit_read_compute).toFixed(1);
				break;
			case 'produce_date':
				// 生产日期
				let _data = _this.tts(_this.highlow_to_num(res_value[0], res_value[1]));
				let y = 2000 + (_data >> 9);
				let m = (_data >> 5) & 0x0f;
				let d = _data & 0x1f;
				_v = `${y}-${m}-${d}`;

				break;

			case 'get_mr':
				// 0xFA指令序号28 获取检流电阻值
				_v = _this.highlow_to_num(res_value[0], res_value[1]);
				// _v = 32793

				// 返回二进制数组 根据最高位判断单位 sttwo默认最后一位是最高位
				let two_arr = _this.sttwo(_v);
				// 单位根据最高位识别，如果为0，则单位是0.1mR；如果为1则单位是0.01mR;
				//例如传送值为10 = 1.0mR，如果传送值为0x800a,最高位为1，则表示单位是0.01，则表示检流电阻为0.1mR
				let unit = 0.1;
				if (two_arr[two_arr.length - 1] == 1) {
					unit = 0.01;
					// 去掉高位得到正常数字
					two_arr[two_arr.length - 1] = 0;
					_v = _this.twoarr_to_num(two_arr);
					// console.log(two_arr, _v, 'two_arr')
				}

				_v = _v * unit;

				uni.setStorageSync('system_setting_current_limit', _v);
				break;

			case 'low4_high4':
				// 返回数据的低四位高四位
				_v = _this.highlow_to_num(res_value[0], res_value[1]); // 64

				// console.log(_this.sttwo(_v))
				// console.log(_this.sttwo(_v, 8, false))
				_v = _this.low4_high4_fun(_v); // {h:4,l:0}
				if (item) {
					// 二级过流保护设置 / 短路保护设置列表初始化

					// console.log(_v, item, '处理前')

					_v = _this.overcurrent_short_fun(_v, item);
				}
				break;

			case 'binary_system':
				// 返回二进制数组 长度16

				if (res_value.length == 2) {
					_v = _this.highlow_to_num(res_value[0], res_value[1]);
				} else {
					_v = res_value[0];
				}
				_v = _this.sttwo(_v);

				if (item) {
					// 十六进制数据后续处理 开启均衡 弱电开关 等按钮
					_this.binary_system_fun(_v, item);
				}

				break;

			case 'binary_system_8':
				// 返回二进制数组 长度8
				if (res_value.length == 2) {
					_v = _this.highlow_to_num(res_value[0], res_value[1]);
				} else {
					_v = res_value[0];
				}
				_v = _this.sttwo(_v, 8);
				break;

			case 'NTC_content':
				// NTC内容
				_v = _this.split_arr_number(res_value, 2).map(ntc => {
					return _this.highlow_to_num(ntc[0], ntc[1]) - 2731;
				});

				break;

			case 'ascii':
				// 1, 1 + res_value[0]
				// res_value[0] 后面有多少个ascii码
				// 1 + res_value[0] 总共需要截取的字符串长度
				_v = res_value
					.slice(1, 1 + res_value[0])
					.map(_mapitem => {
						if (_mapitem > 0) {
							return _this.back_ascii_number(_mapitem);
						}
					})
					.join('');

				break;

			case 'information_bmsAddress':
				_v = res_value.join('');
				break;
			case 'is_temperature':
				// 温度
				_v = (_this.highlow_to_num(res_value[0], res_value[1]) - 2731) / 10;
				break;
			case 'default':
				_v = _this.highlow_to_num(res_value[0], res_value[1]);
				break;
		}
		return _v;
	},
	value_handle_arr(edit_value, value_type, item = false) {
		let _this = this;
		let _v;
		switch (value_type) {
			case 'is_current':
				// [0,1] - 1  - fun
				// 带符号型16进制数，通过电流判断电池充放电状态，充电为正，放电为负。例如充电1A，传输数值为0x0064,放电1A传输数值为0X10000 -0X0064 = 0Xff9c
				if (edit_value > 0) {
					// 正数
				} else {
					// 负数
					edit_value = 65536 - Math.abs(edit_value);
				}
				_v = _this.num_to_highlow(edit_value).hl;
				break;

			case 'resistance':
				// 连接内阻
				let unit_read_compute = 0.1;
				edit_value = Math.floor(edit_value / unit_read_compute);
				// console.log(edit_value, 'floor')
				if (edit_value > 0) {
					// 正数
				} else {
					// 负数
					edit_value = 65536 - Math.abs(edit_value);
				}
				_v = _this.num_to_highlow(edit_value).hl;

				break;

			case 'binary_system':
				_v = _this.twoarr_to_num(edit_value);
				_v = _this.num_to_highlow(_v).hl;
				break;
			case 'binary_system_8':
				_v = _this.twoarr_to_num(edit_value);
				_v = _this.num_to_highlow(_v).hl;

				break;
			case 'NTC_content':
				// NTC内容
				// _v = _this.split_arr_number(edit_value, 2).map((ntc) => {
				//     return _this.highlow_to_num(ntc[0], ntc[1]) - 2731
				// });

				break;

			case 'ascii_nolength':
				_v = edit_value.split('').map(item => {
					return _this.back_ascii_number(item);
				});

				break;

			case 'ascii':
				// 1, 1 + edit_value[0]
				// edit_value[0] 后面有多少个ascii码
				// 1 + edit_value[0] 总共需要截取的字符串长度
				_v = edit_value.split('').map(item => {
					return _this.back_ascii_number(item);
				});
				_v.unshift(_v.length);
				break;

			case 'information_bmsAddress':
				_v = edit_value.join('');
				break;
			case 'is_temperature':
				// 温度
				_v = edit_value * 10 + 2731;
				_v = _this.num_to_highlow(_v).hl;
				break;
			case 'low4_high4':
				_v = _this.num_to_highlow(edit_value).hl;
				break;
			case 'default':
				// edit_value = parseFloat(edit_value);
				// let _number = parseFloat(edit_value);
				_v = _this.num_to_highlow(edit_value).hl;
				// let end = _this.highlow_to_num(_v[0], _v[1])
				break;
		}
		return _v;
	},

	// 十进制转十六进制
	tts(decimalValue, zero = true) {
		let _this = this;
		// console.log(decimalValue)
		let hexString = decimalValue.toString(16).toUpperCase();
		// if (_this.objJudge(decimalValue)) {
		//     // console.log(decimalValue)
		//     hexString = decimalValue.toString(16).toUpperCase();
		// } else {
		//     // console.log(decimalValue)
		// }

		if (zero) {
			// 补零操作，确保输出为二位
			while (hexString.length < 2) {
				hexString = '0' + hexString;
			}
			return `0x${hexString}`;
		} else {
			return hexString;
		}
	},

	twoarr_to_num(bitsArray) {
		let result = 0;
		for (let i = 0; i < bitsArray.length; i++) {
			// 高位在前的情况
			// result += bitsArray[bitsArray.length - 1 - i] << i;

			// 高位在后的情况
			result += bitsArray[i] << i;
		}
		return result;
	},

	/**
	 * v 为字符串则输出 ascii码
	 * v 为ascii码则输出 字符串
	 * @param {number,string} v
	 */
	back_ascii_number(v) {
		let _this = this;
		let type = _this.gettype(v);
		let _b = '';
		if (type == 'String') {
			_b = v.charCodeAt(0);
		} else if (type == 'Number') {
			_b = String.fromCharCode(v);
		}
		return _b;
	},
	// [0,1,2,3] -> [[0,1],[2,3]]
	split_arr_number(arr, n = 2) {
		var back = [];
		for (var i = 0; i < arr.length; i += n) {
			back.push(arr.slice(i, i + n));
		}
		// 输出拆分后的数组，每个子数组长度为2
		return back;
	},

	arr_reverse(arr) {
		for (let i = 0; i < arr.length - 1; i += 2) {
			let temp = arr[i];
			arr[i] = arr[i + 1];
			arr[i + 1] = temp;
		}
		return arr;
		// [0,1,2,3,4,5]
		// 输出 [1, 0, 3, 2, 5, 4]
	},

	// 写入数据
	// pageBuffer -> 指定哪个页面 ?
	writeBufferToBLE(event) {
		let { start = 0xdd, id, cmd, dataLen, _buffer, force_write, callback = false } = event;
		// let sendArray = [0xdd, id, cmd, dataLen];
		let _this = this;
		// console.log(_this.bluetooth_can_write, _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_connect, '_this.bluetooth_can_write');
		if (!_this.bluetooth_can_write) return;
		if (!_this.BLUETOOTH_DEVICE_CONFIG.bluetooth_connect) return;
		// 1.初始化参数 id => 类型指令 读或者写
		let init_arr = [start];
		if (id) {
			init_arr.push(id);
		}
		let send_arr = [];

		if (_this.gettype(cmd) == 'String') {
			cmd = Number(cmd);
		}

		// 2.初始化需要校验的参数  命令码 数据长度
		let need_check = [cmd, dataLen];

		// 3.页面buffer数据写入数组中
		if (_this.objJudge(_buffer)) {
			let _buffer_length = _buffer.length;
			for (let i = 0; i < _buffer_length; i++) {
				need_check.push(_buffer[i]);
			}
		}

		// 4.校验蓝牙数据
		// console.log(need_check, 'need_check 校验前')
		need_check = _this.check_buffer(need_check);
		// console.log(need_check, 'need_check 校验后')

		// 5.校验蓝牙数据后合并初始数组 init_arr
		send_arr = init_arr.concat(need_check);
		//  --------------------------- 直接写入指令 start
		// 覆盖指令
		// [0xFF, 0xAA, 0x00, 0x00, 0x00] 读取mac地址
		if (_this.objJudge(force_write)) {
			send_arr = force_write;
		}
		//  --------------------------- 直接写入指令 end

		// 6.send_arr => 处理成写入的arrayBuffer数据
		let send_buffer = new ArrayBuffer(send_arr.length);
		let send_view = new DataView(send_buffer);

		// console.log(send_buffer);
		// console.log(send_view);
		for (let i = 0; i < send_arr.length; i++) {
			let v = send_arr[i];
			send_view.setUint8(i, v);
		}
		_this.log_buffer(send_buffer, '【开始写入-111111111111111】');
		_this.writeBufferToBLE_judge(send_buffer, callback);
	},

	// 判断是否分包写入
	writeBufferToBLE_judge(send_buffer, callback = false) {
		let _this = this;
		let package_size = 20;
		let value_length = send_buffer.byteLength;
		let value = send_buffer;
		let new_value = [];
		let deviceId = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_deviceId;
		let serviceId = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_serviceId;
		let characteristicId = _this.BLUETOOTH_DEVICE_CONFIG.bluetooth_writeCharacteristicId;
		// console.log({
		//     deviceId,
		//     serviceId,
		//     characteristicId
		// })

		// 设备接收超过20字节需要分包写入
		if (value_length > 20) {
			value = send_buffer.slice(0, package_size);
			new_value = send_buffer.slice(package_size);
		}

		// console.log(deviceId, serviceId, characteristicId)

		if (deviceId && serviceId && characteristicId) {
			wx.writeBLECharacteristicValue({
				deviceId,
				serviceId, // 在这里替换成你的设备服务ID
				characteristicId, // 在这里替换成你的设备特征ID
				value,
				success: function (res) {
					if (value_length <= 20) {
						callback && callback();
						console.log('2.writeBufferToBLE-写入完成');
					} else {
						_this.writeBufferToBLE_judge(new_value, callback);
						console.log('2.writeBufferToBLE-分包写入中');
					}
				},
				fail(err) {
					console.log('writeBufferToBLE-写入失败');
				},
			});
		}
	},

	check_buffer(arr, mode = 'default') {
		// 为数据段内容+长度字节+命令码字节的校验和然后在取反加1,
		let _this = this;
		let _t = arr.reduce((pre, next) => {
			return pre + next;
		}, 0);

		if (mode == 'base') {
			// 蓝牙基础修改指令
			// arr.push(_t)
			// arr.push(_this.num_to_highlow(_t).h)
			arr.push(_this.num_to_highlow(_t).l);
		} else {
			// console.log(_t, '总和');
			// console.log((~_t), '取反');
			// console.log((~_t) + 1, '取反+1');
			let _end = (~_t + 1) & 0xffff;
			// console.log(_end, '0xFFFF');
			// console.log(_this.num_to_highlow(_end), '0xFFFF');

			// 高位在前，低位在后
			arr.push(_this.num_to_highlow(_end).h);
			arr.push(_this.num_to_highlow(_end).l);
			arr.push(0x77); //硬件结束符
		}

		return arr;
	},
	// 获取值的低四位高四位 64
	low4_high4_fun(v, log = false) {
		let l = v & 0b1111; // 0
		let h = (v >> 4) & 0b1111; // 4
		// let hl = [h, l];
		if (log) {
			console.log({
				v,
				h,
				l,
			});
		}
		return {
			h,
			l,
		};
	},

	// 低四位高四位返回值
	low4_high4_rever_fun(h, l, log = false) {
		let back = (h << 4) + l;
		if (log) {
			console.log(h, l, back);
		}
		return back;
	},

	// 8高位 8低位
	num_to_highlow(v, log = false) {
		let h = (v >> 8) & 0xff; // 21
		let l = v & 0xff; // 51
		let h_str = this.tts(h); // 十六进制高位
		let l_str = this.tts(l); // 十六进制低位.
		let hl = [h, l];
		if (log) {
			console.log({
				v,
				h,
				h_str,
				l,
				l_str,
				hl,
			});
		}
		return {
			h,
			h_str,
			l,
			l_str,
			hl,
		};
	},
	highlow_to_num(h, l, log = false) {
		let back = (h << 8) | l;
		// console.log({ dataLenHigh, dataLenLow })

		// console.log({ back })
		if (log) {
			console.log(h, l, back);
		}
		return back;
	},
};
